package com.clip.service;

import java.math.BigDecimal;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.clip.dao.AlertUserDAO;
import com.clip.dao.ClipAddressrefDAO;
import com.clip.dao.ClipEventDao;
import com.clip.dao.ClipeventPicDAO;
import com.clip.dao.ClipmessageDAO;
import com.clip.dao.ContactDAO;
import com.clip.dao.ContactGroupMappingDAO;
import com.clip.dao.ContactTypeDAO;
import com.clip.dao.ForbiddenEventDAO;
import com.clip.dao.MsgNoticeDAO;
import com.clip.dao.RequestmappingDAO;
import com.clip.dao.ShareacceptmappingDAO;
import com.clip.dao.SharefavormappingDAO;
import com.clip.dao.SharemappingDAO;
import com.clip.dao.SystemMessageDAO;
import com.clip.dao.UserDAO;
import com.clip.dao.UserDevicetokenDAO;
import com.clip.dao.UserEmailDAO;
import com.clip.dao.UsermobileinfoDAO;
import com.clip.entity.AlertUser;
import com.clip.entity.ClipAddressref;
import com.clip.entity.ClipEvent;
import com.clip.entity.ClipeventPic;
import com.clip.entity.Clipmessage;
import com.clip.entity.Contact;
import com.clip.entity.ContactType;
import com.clip.entity.ForbiddenEvent;
import com.clip.entity.MsgNotice;
import com.clip.entity.Requestmapping;
import com.clip.entity.ShareAcceptmapping;
import com.clip.entity.ShareEvent;
import com.clip.entity.ShareFavormapping;
import com.clip.entity.Sharemapping;
import com.clip.entity.SystemMessage;
import com.clip.entity.User;
import com.clip.entity.UserDevicetoken;
import com.clip.entity.UserEmail;
import com.clip.entity.Usermobileinfo;
import com.clip.entity.virtual.EventForView;
import com.clip.exception.ClipEventNotExistException;
import com.clip.job.AlertJob;
import com.clip.util.ToolsUtils;
import com.clip.util.URLReplace;
import com.clip.util.mail.SimpleMailSender;
import com.clip.util.mobile.MobileHttpSender;
import com.clip.util.mobile.MobileMsgPattern;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.DateBuilder.*;
@Service
@Transactional
public class EventService {
	
	public static int MEMOPERPAGE=6;
	
	public static int SHAREEVENTLOADLENGTH=20;
	public static int QUICKSHAREEVENTLOADLENGTH=20;
	@Autowired
	private ClipEventDao clipEventDao;
	@Autowired
	private AlertUserDAO alertUserDAO;
	@Autowired
	private ForbiddenEventDAO forbiddenEventDAO;
	@Autowired
	private ContactDAO contactDAO;
	@Autowired
	private ContactTypeDAO contactTypeDAO;
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private UserEmailDAO userEmailDAO;
	@Autowired
	private UsermobileinfoDAO usermobileinfoDAO;
	@Autowired
	private ClipmessageDAO clipmessageDAO;
	@Autowired
	private SharemappingDAO sharemappingDAO;
	@Autowired
	private ShareacceptmappingDAO shareacceptmappingDAO;
	@Autowired
	private ContactGroupMappingDAO contactGroupMappingDAO;
	@Autowired
	private MsgNoticeDAO msgNoticeDAO;
	@Autowired
	private SharefavormappingDAO sharefavormappingDAO;
	@Autowired
	private ClipAddressrefDAO addressrefDAO;
	@Autowired
	private ClipeventPicDAO clipeventPicDAO;
	@Autowired
	private UserDevicetokenDAO userDevicetokenDAO;
	@Autowired
	private SystemMessageDAO systemMessageDAO;
	@Autowired
	private RequestmappingDAO requestmappingDAO;
	/**
	 * 删除的档期，必定是reliedclip=0的档期
	 * 
	 * @param currentUser
	 * @param eventid
	 * @return
	 */
	public String deleteEvent(User currentUser, Integer eventid) {
		if(eventid>0){
			ClipEvent clipEvent=this.clipEventDao.findById(eventid);
			if(clipEvent==null||clipEvent.getUid()!=currentUser.getId())
				return "档期不存在或无权操作";
			int cliptype=clipEvent.getCliptype();
			if(cliptype==2){
				this.clipEventDao.delete(clipEvent);
				return null;
			}
			if(clipEvent.getStatus()==0&&clipEvent.getReliedclip()==0){
				this.clipEventDao.delete(clipEvent);
				return null;
			}
			if(cliptype==1){
				//直接删除
				this.clipEventDao.delete(clipEvent);
				//删除提醒
				removeQuartz("clipevent_"+clipEvent.getId());
			}
			
			if(clipEvent.getStatus()==2){
				//在回收站内的删除
				this.clipEventDao.delete(clipEvent);
				if(clipEvent.getReliedclip()>0)
					removeContactList(clipEvent.getReliedclip(),currentUser.getId());
				return null;
			}else{
				if(cliptype==3){
					int eventtype=clipEvent.getEventtype();
					int seid=clipEvent.getSeid();
					if(eventtype==2&&seid==0){//说明商家是发起人，商家删除自己的档期
						/**
						 * 是否需要通知所有用户，即 clipevent.seid=eventid的事件用户，通知
						 * sql="select distinct(event.uid) from ClipEvent event where event.seid=eventid"
						 */
						String uidsQuerysql="select event.uid,event.id from ClipEvent event where event.seid="+clipEvent.getId();
						List list=this.clipEventDao.findByQuery(uidsQuerysql);
						List<Integer> uidslist=new ArrayList<Integer>();//通知的用户列表
						for (Object object : list) {
							Object[] objs=(Object[]) object;
							if(!uidslist.contains(objs[0])){
								uidslist.add((Integer)objs[0]);
							}
							removeQuartz("clipevent_"+(Integer)objs[1]);
						}
						String delShareAcceptmappingSQL="delete from ShareAcceptmapping map where map.eventid="+clipEvent.getId();
						this.shareacceptmappingDAO.updateByQuery(delShareAcceptmappingSQL);
						String delShareFavormappingSQL="delete from ShareFavormapping map where map.eventid="+clipEvent.getId();
						this.sharefavormappingDAO.updateByQuery(delShareFavormappingSQL);
						String delSharemappingSQL="delete from Sharemapping map where map.eventid="+clipEvent.getId();
						this.sharemappingDAO.excuteUpdateQuery(delSharemappingSQL);
						//暂不考虑删除评论
						String batchUpdateSQL="update ClipEvent event set event.status=2 , event.processstatus=2 where event.seid="+clipEvent.getId();
						this.clipEventDao.updateByQuery(batchUpdateSQL);
						for (Integer uid : uidslist) {
							SystemMessage message=new SystemMessage();
							message.setEventid(clipEvent.getId());
							message.setFromuid(clipEvent.getUid());
							message.setMsgtime(Calendar.getInstance().getTimeInMillis());
							message.setMsgtype(SystemMessage.CANCELTYPE);
							message.setUid(uid);
							message.setCheckstatus(0);
							this.systemMessageDAO.save(message);
							sendCCCancelEmail(currentUser,uid,clipEvent);
							////////////////////////////////sendCancelInvitedEmail(currentUser,clipEvent);//商家取消档期的邮件通知
						}
						clipEvent.setProcessstatus(2);
						clipEvent.setStatus(2);
						this.clipEventDao.attachDirty(clipEvent);
					}else{
						String sharemappingSQL="select map.share2uid from Sharemapping map where map.acceptstatus=1 and map.eventid="+clipEvent.getId();
						List list=this.sharemappingDAO.findByQuery(sharemappingSQL);
						for (Object object : list) {
							int share2uid=(Integer) object;
							SystemMessage message=new SystemMessage();
							message.setEventid(clipEvent.getId());
							message.setFromuid(clipEvent.getUid());
							message.setMsgtime(Calendar.getInstance().getTimeInMillis());
							message.setMsgtype(SystemMessage.CANCELTYPE);
							message.setUid(share2uid);
							this.systemMessageDAO.save(message);
							sendCancelShareEventEmail(currentUser,share2uid, clipEvent);//用户取消档期的邮件通知
						}
							//个人 呼朋唤友
							//删除呼朋唤友的链
//						String delSharemappingSQL="delete from Sharemapping map where map.eventid="+clipEvent.getId();
//						this.sharemappingDAO.excuteUpdateQuery(delSharemappingSQL);
							//删除感兴趣的链
						if(clipEvent.getEventtype()==2){
							String queryShareAcceptmappingSQL="from ShareAcceptmapping map where map.accepttype=1 and map.eventid="+clipEvent.getId();
							List shareAcceptmappingList=this.shareacceptmappingDAO.findByQuery(queryShareAcceptmappingSQL);
							for (Object object : shareAcceptmappingList) {
								ShareAcceptmapping acceptmapping=(ShareAcceptmapping) object;
								int feventid=acceptmapping.getFolloweventid();
								String delShareAcceptmappingSQL=
									"delete from ShareAcceptmapping map where map.accepttype=3 and map.followeventid="+feventid+" and map.eventid="+clipEvent.getSeid();
								
								this.shareacceptmappingDAO.excuteUpdateQuery(delShareAcceptmappingSQL);
							}
						}
						String delShareAcceptmappingSQL="delete from ShareAcceptmapping map where map.accepttype=1 and map.eventid="+clipEvent.getId();
						this.shareacceptmappingDAO.excuteUpdateQuery(delShareAcceptmappingSQL);
							//删除标记感兴趣的用户的档期
						String sql="update ClipEvent event set event.status=2, event.processstatus=2 where event.reliedclip="+clipEvent.getId();
						this.clipEventDao.updateByQuery(sql);
						String delAlertUserSQL="delete from AlertUser au where au.eventid="+clipEvent.getId();
						this.alertUserDAO.excuteUpdateQuery(delAlertUserSQL);
						clipEvent.setProcessstatus(2);
						clipEvent.setStatus(2);
						this.clipEventDao.attachDirty(clipEvent);
					}
					return null;
				}else if(cliptype==4){
					this.clipEventDao.delete(clipEvent);
					//删除提醒
					removeQuartz("clipevent_"+clipEvent.getId());
					return null;
				}else
					return "数据错误";
				
			}
		}else{
			return "数据错误";
		}
	}

	private void sendCCCancelEmail(User currentUser,int informeduid, ClipEvent clipEvent) {
		String url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/recycle_detail.html?eventid="+clipEvent.getId();
		List<UserEmail> userEmails=userEmailDAO.findByQuery("from UserEmail ue where ue.bindable=1 and ue.status=1 and ue.uid="+informeduid);
		User informedUser=this.userDAO.findById(informeduid);
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("ccuname", currentUser.getName());
		root.put("informedname", informedUser.getName());
		root.put("url", url);
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"cccancelclip.ftl");
		for (UserEmail userEmail : userEmails) {
			SimpleMailSender.send(mailcontent, informedUser.getName()+"，你有一个来自档期的消息", userEmail.getEmail());
		}
	}
	
	private void sendCancelShareEventEmail(User currentUser,int share2uid, ClipEvent clipEvent) {
		String url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/recycle_detail.html?eventid="+clipEvent.getId();
		List<UserEmail> userEmails=userEmailDAO.findByQuery("from UserEmail ue where ue.bindable=1 and ue.status=1 and ue.uid="+share2uid);
		User informedUser=this.userDAO.findById(share2uid);
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("canceledname", currentUser.getName());
		root.put("informedname", informedUser.getName());
		root.put("title", clipEvent.getTitle());
		root.put("url", url);
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"cancelinvitedevent.ftl");
		for (UserEmail userEmail : userEmails) {
			SimpleMailSender.send(mailcontent, informedUser.getName()+"，你有一个来自档期的消息", userEmail.getEmail());
		}
	}

	public ClipEvent modifyEvent(User currentUser, Integer eventid) {
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		if(clipEvent.getReliedclip()==0){
			if(clipEvent.getCliptype()==3){
				String temp="delete from ShareAcceptmapping map where map.eventid="+clipEvent.getId();
				this.shareacceptmappingDAO.updateByQuery(temp);
				this.clipEventDao.updateByQuery("delete from ClipEvent event where event.reliedclip="+clipEvent.getId());
			}
			this.clipEventDao.delete(clipEvent);
			removeQuartz("clipevent_"+clipEvent.getId());
			stopJoinsEvent(eventid);
			clipEvent.setId(0);
			clipEvent.setReliedclip(0);
			clipEvent.setIsvip(0);
			clipEvent.setIsread(1);
			clipEvent.setStatus(0);
			clipEvent.setProcessstatus(0);
			Date now=new Date(); 
			clipEvent.setUpdatetime(now.getTime());
			clipEvent.setEventtype(currentUser.getUsertype());
			this.clipEventDao.save(clipEvent);
//			sendCancelInvitedEmail(currentUser,clipEvent);
			return clipEvent;
		}else 
			return null;
	}
	
	public ClipEvent rebackEvent(User currentUser, Integer eventid,Calendar now) {
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		if(clipEvent.getReliedclip()>0){
			clipEvent.setStatus(0);
			clipEvent.setIsread(0);
			ClipEvent clipOwner=this.clipEventDao.findById(clipEvent.getReliedclip());
			if(clipOwner!=null){
				updateOverDeadlinetime(clipOwner, now);
				clipEvent.setProcessstatus(clipOwner.getProcessstatus());
			}else{
				clipEvent.setProcessstatus(2);
			}
		}else{
			this.clipEventDao.delete(clipEvent);
			clipEvent.setId(0);
			clipEvent.setReliedclip(0);
			clipEvent.setIsvip(0);
			clipEvent.setIsread(1);
			clipEvent.setStatus(0);
			clipEvent.setProcessstatus(0);
			clipEvent.setUpdatetime(now.getTimeInMillis());
			clipEvent.setEventtype(currentUser.getUsertype());
			this.clipEventDao.save(clipEvent);
		}
		return clipEvent;
	}
	
	private void changeAlertUserStatus(User currentUser,ClipEvent clipEvent,int status,boolean isneednotice) {
		AlertUser alertUser=(AlertUser) this.alertUserDAO.findByQuery("from AlertUser au where au.eventid="+clipEvent.getReliedclip()+" and au.contactuid="+clipEvent.getUid()).get(0);
		alertUser.setStatus(status);
		this.alertUserDAO.attachDirty(alertUser);
		if(isneednotice)
			sendRefuseEmailToPublisher(alertUser.getUid(), currentUser.getName(), clipEvent.getReliedclip());
	}

	private void stopJoinsEvent(Integer eventid) {
		this.clipEventDao.updateByQuery("update ClipEvent ce set ce.processstatus=2 where ce.reliedclip="+eventid);
	}

	public String finishEvent(User currentUser, Integer eventid,Calendar calendar) {
		if(eventid>0){
			ClipEvent clipEvent=this.clipEventDao.findById(eventid);
			ForbiddenEvent forbiddenEvent=new ForbiddenEvent();
			forbiddenEvent.setEventid(eventid);
			forbiddenEvent.setUid(currentUser.getId());
			forbiddenEvent.setUpdatetime(calendar.getTimeInMillis());
			forbiddenEventDAO.save(forbiddenEvent);
			return null;
		}else
			return "数据错误";
	}
	
	public String cancelClock(User currentUser, Integer eventid) {
		if(eventid>0){
			ClipEvent clipEvent=this.clipEventDao.findById(eventid);
			
			if(clipEvent.getUid()!=currentUser.getId()&&clipEvent.getReliedclip()==0){
				//可能是感兴趣档期，找出ShareAcceptmapping
				String shareacceptmappingSQL="from ShareAcceptmapping map where map.eventid=? and map.uid=? and map.accepttype=1";
				List list=this.shareacceptmappingDAO.findByQuery(shareacceptmappingSQL, new Object[]{eventid,currentUser.getId()});
				if(list!=null&&list.size()==1){
					ShareAcceptmapping acceptmapping=(ShareAcceptmapping) list.get(0);
					int fleventid=acceptmapping.getFolloweventid();
					ClipEvent userClipEvent=this.clipEventDao.findById(fleventid);
					userClipEvent.setAlerttime(0l);
					userClipEvent.setMobilenotice(0);
					this.clipEventDao.attachDirty(userClipEvent);
					removeQuartz("clipevent_"+userClipEvent.getId());
					return null;
				}
			}else if(clipEvent.getUid()==currentUser.getId()){
				clipEvent.setAlerttime(0l);
				clipEvent.setMobilenotice(0);
				this.clipEventDao.attachDirty(clipEvent);
				removeQuartz("clipevent_"+clipEvent.getId());
				return null;
			}
			return "数据错误";
		}else
			return "数据错误";
	}
	
	public String app_CancelClock(User currentUser, Integer eventid) {
		if(eventid>0){
			ClipEvent clipEvent=this.getDetailClipEvent(eventid);
			if(clipEvent.getUid()!=currentUser.getId()){
				return "无权操作此档期";
			}else{
				clipEvent.setAlerttime(0l);
				clipEvent.setMobilenotice(0);
				this.clipEventDao.attachDirty(clipEvent);
				//1.删除quartz
				removeQuartz("clipevent_"+clipEvent.getId());
				return null;
			}
		}else
			return "数据错误";
	}
	
	/*public String getDetailEvent(Integer eventid) {
		if(eventid>0){
			ClipEvent clipEvent=getClipEventById(eventid);
			StringBuffer str=new StringBuffer();
			str.append("{result:1,eventid:'");
			str.append(clipEvent.getId());
			str.append("',title:'");
			str.append(clipEvent.getTitle());
			str.append("',address:'");
			str.append(clipEvent.getAddress()==null||clipEvent.getAddress().length()==0?"":clipEvent.getAddress());
			str.append("',content:'");
			str.append(clipEvent.getContent()==null||clipEvent.getContent().length()==0?"":clipEvent.getContent());
			str.append("',eventtype:'");
			str.append(ClipEvent.eventtypeInt2Str(clipEvent.getEventtype()));
			str.append("',starttime:");
			str.append(clipEvent.getBegintime());
			str.append(",endtime:");
			str.append(clipEvent.getEndtime());
			str.append(",alerttime:");
			str.append(clipEvent.getAlerttime());
			
			str.append("}");
			return str.toString();
		}else{
			return "{result:1,msg:'数据错误'}";
		}
	}*/
	
	public ClipEvent getClipEventById(Integer eventid){
		return this.clipEventDao.findById(eventid);
	}
	
	public ClipEvent getDetailShareEvent(String uuid){
		ClipEvent clipEvent=null;
		Calendar now=Calendar.getInstance();
		List list=this.clipEventDao.findByProperty(ClipEventDao.SHAREID, uuid);
		if(list!=null&&list.size()==1){
			clipEvent=(ClipEvent) list.get(0);
			if(clipEvent.getStatus()==1){
				int parentid=clipEvent.getReliedclip();
				if(parentid>0){
					ClipEvent parentEvent=this.clipEventDao.findById(parentid);
					if(parentEvent!=null&&parentEvent.getStatus()==1){
						updateOverDeadlinetime(parentEvent,now);
						updateOverDeadlinetime(clipEvent,now);
					}else{
						return null;
					}
				}
			}else
				return null;
		}else{
			return null;
		}
		return clipEvent;
	}
	
	public ClipEvent getDetailClipEvent(Integer eventid){
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		if(clipEvent==null)
			return null;
		if(clipEvent.getStatus()!=2){
			clipEvent.setIsread(1);
			this.clipEventDao.attachDirty(clipEvent);
			Calendar now=Calendar.getInstance();
			updateOverDeadlinetime(clipEvent,now);
		}
		return clipEvent;
	}
	
//	private String getContactlistByEventid(Integer eventid) {
//		List list=this.alertUserDAO.findByEventid(eventid);
//		StringBuffer sb=new StringBuffer();
//		sb.append("'");
//		for (int i = 0; i < list.size(); i++) {
//			AlertUser alertUser = (AlertUser) list.get(i);
//				sb.append(alertUser.getContactid());
//		}
//		return sb.toString();
//	}


	private void removeQuartz(String triggername) {
		try {
			Scheduler scheduler=StdSchedulerFactory.getDefaultScheduler();
			scheduler.unscheduleJob(new TriggerKey(triggername,Scheduler.DEFAULT_GROUP));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	private boolean isMobileNoticeUser(String mobilelist,int uid){
		if(mobilelist==null||mobilelist.trim().length()==0)
			return false;
		boolean flag1=false,flag2=false;
		if(mobilelist.indexOf(",")>0){
			String []ids=mobilelist.split(",");
			for (String id : ids) {
				Integer cid=Integer.parseInt(id);
				if(cid==uid){
					flag1=true;
					break;
				}
			}
		}else{
			Integer cid=Integer.parseInt(mobilelist);
			if(cid==uid){
				flag1=true;
			}
		}
		String query="from Usermobileinfo info where info.status=1 and info.uid="+uid;
		List list=this.usermobileinfoDAO.findByQuery(query);
		if(list!=null&&list.size()>0){
			flag2=true;
		}
		return flag1&&flag2;
	}
	
	private void saveContactList(ClipEvent clipEvent,User currentUser, String contactlist,String mobilelist,Boolean isCreateCopy) {
		if(contactlist!=null&&contactlist.length()>0){
			if(contactlist.indexOf(",")>0){
				String []uids=contactlist.split(",");
				for (String id : uids) {
					Integer contactuid=Integer.parseInt(id);
					Contact contact=(Contact) this.contactDAO.findByQuery("from Contact c where c.uid="+currentUser.getId()+" and c.contactuid="+contactuid).get(0);
					int flag=this.isMobileNoticeUser(mobilelist, contactuid)?1:0;
					ClipEvent followclip=(ClipEvent) clipEvent.clone();
					if(isCreateCopy){
						followclip.setId(0);
						followclip.setStatus(0);
						followclip.setReliedclip(clipEvent.getId());
						followclip.setUpdatetime(0l);
						followclip.setUid(contact.getContactuid());
						followclip.setIsread(0);
						followclip.setEventtype(1);
						followclip.setAlerttime(0l);
						followclip.setCliptype(1);
						this.clipEventDao.save(followclip);
						sendInvitedEmail(currentUser.getName(),contact.getContactuid(),followclip,flag);
					}
					AlertUser alertUser=new AlertUser();
					alertUser.setEventid(clipEvent.getId());
					alertUser.setUid(currentUser.getId());
					alertUser.setContactid(contact.getId());
					alertUser.setContactuid(contact.getContactuid());
					alertUser.setMobilenotice(flag);
					alertUser.setStatus(0);
					alertUser.setFolloweventid(followclip.getId());
					alertUserDAO.save(alertUser);
				}
			}else{
				Integer uid=Integer.parseInt(contactlist);
				Contact contact=(Contact) this.contactDAO.findByQuery("from Contact c where c.uid="+currentUser.getId()+" and c.contactuid="+uid).get(0);
				int flag=this.isMobileNoticeUser(mobilelist, uid)?1:0;
				ClipEvent fClip=(ClipEvent) clipEvent.clone();
				if(isCreateCopy){
					fClip.setId(0);
					fClip.setStatus(0);
					fClip.setReliedclip(clipEvent.getId());
					fClip.setUpdatetime(0l);
					fClip.setUid(uid);
					fClip.setIsread(0);
					fClip.setEventtype(1);
					fClip.setAlerttime(0l);
					fClip.setCliptype(1);
					this.clipEventDao.save(fClip);
					sendInvitedEmail(currentUser.getName(),uid,fClip,flag);
				}
				AlertUser alertUser=new AlertUser();
				alertUser.setEventid(clipEvent.getId());
				alertUser.setUid(currentUser.getId());
				alertUser.setContactid(contact.getId());
				alertUser.setContactuid(uid);
				alertUser.setMobilenotice(flag);
				alertUser.setStatus(0);
				alertUser.setFolloweventid(fClip.getId());
				alertUserDAO.save(alertUser);
			}
		}
	}

	/**
	 * @param currentUsername currentusername
	 * @param uid 2inviteusername
	 * @param clipEvent
	 * @param sendmobilemsgflag
	 */
	private void sendInvitedEmail(String currentUsername, Integer uid, ClipEvent clipEvent,int sendmobilemsgflag) {
		String url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/clip_detail.html?"+clipEvent.getShareid();
		
		User user=this.userDAO.findById(uid);
		List<UserEmail> userEmails=userEmailDAO.findByQuery("from UserEmail ue where ue.bindable=1 and ue.status=1 and ue.uid="+uid);
		if(userEmails!=null&&userEmails.size()>0){
			Map<String, Object> root = new HashMap<String, Object>();
			root.put("pname", currentUsername);
			root.put("fname", user.getName());
			root.put("title", clipEvent.getTitle());
			root.put("url", url);
			String mailcontent = com.clip.util.FtlUtils.stringRender(root,"invitedevent.ftl");
			for (UserEmail userEmail : userEmails) {
				SimpleMailSender.send(mailcontent,user.getName() +"，你有一个来自档期的消息", userEmail.getEmail());
			}
		}
	}

	public ClipEvent createClipEvent(Integer cliptype,String title, String address, String content,
			Long begintime, Long endtime, Long alerttime,Long deadlinetime,
			User currentUser, Calendar now,Integer status,int mobilenotice, String mobilelist,
			Integer iswholeday,String share2userlist
			) {
		ClipEvent clipEvent=new ClipEvent();
		clipEvent.setTitle(title);
		if(address!=null&&content.length()>0)
		clipEvent.setAddress(address);
		if(content!=null&&content.length()>0)clipEvent.setContent(content);
		if(currentUser.getUsertype()==1){
			clipEvent.setEventtype(1);
		}else{
			clipEvent.setEventtype(2);
		}
		clipEvent.setBegintime(begintime);
		clipEvent.setIswholeday(iswholeday);
		if(iswholeday==1&&(cliptype==1||cliptype==3||cliptype==4)){
			Calendar calendar=Calendar.getInstance();
			calendar.setTimeInMillis(begintime);
			calendar.clear(Calendar.MILLISECOND);
			calendar.clear(Calendar.SECOND);
			calendar.clear(Calendar.MINUTE);
			calendar.set(Calendar.HOUR_OF_DAY,0);
			calendar.add(Calendar.DATE, 1);
			calendar.add(Calendar.SECOND, -1);
			endtime=calendar.getTimeInMillis();
		}else{
			Calendar calendar=Calendar.getInstance();
			calendar.setTimeInMillis(endtime);
			calendar.clear(Calendar.MILLISECOND);
			calendar.clear(Calendar.SECOND);
			endtime=calendar.getTimeInMillis();
		}
		clipEvent.setEndtime(endtime);
		clipEvent.setUid(currentUser.getId());
		clipEvent.setCliptype(cliptype);
		clipEvent.setCreatetime(now.getTimeInMillis());
		if(cliptype==2){
			Calendar calendar=Calendar.getInstance();
			calendar.setTimeInMillis(begintime);
			SimpleDateFormat dateFormat=new SimpleDateFormat("MMdd");
			Long tmp=Long.parseLong("1"+dateFormat.format(calendar.getTime()));
			clipEvent.setEndtime(tmp);
			if(alerttime!=null&&alerttime>0l)
				clipEvent.setAlerttime(alerttime);
			clipEvent.setStatus(status);
			clipEvent.setIswholeday(1);
			this.clipEventDao.save(clipEvent);
			addClipEventClock(alerttime,clipEvent,mobilenotice);
			return clipEvent;
		}
		clipEvent.setReliedclip(0);
		clipEvent.setIsvip(0);
		clipEvent.setIsread(1);
		clipEvent.setStatus(status);
		if(now.getTimeInMillis()<clipEvent.getBegintime())
			clipEvent.setProcessstatus(-1);
		else{
			clipEvent.setProcessstatus(0);
		}
		if(status==0){
			clipEvent.setUpdatetime(now.getTimeInMillis());
			this.clipEventDao.save(clipEvent);
			return clipEvent;
		}else{
			
			clipEvent.setUpdatetime(0l);
//			if(deadlinetime!=null&&deadlinetime>0l)
//				clipEvent.setDeadlinetime(deadlinetime);
			if(alerttime!=null&&alerttime>0l)
				clipEvent.setAlerttime(alerttime);
			if(alerttime!=null&&alerttime>0l){
				if(checkUserHasMobile(currentUser.getId())&&mobilenotice==1){
					clipEvent.setMobilenotice(mobilenotice);
				}
			}else{
				clipEvent.setMobilenotice(0);
			}
			this.clipEventDao.save(clipEvent);
			if(clipEvent.getCliptype()==3){
				if(currentUser.getUsertype()!=2){
					if(share2userlist!=null&&share2userlist.length()>0){
						saveShare2userList(currentUser,clipEvent,share2userlist,mobilelist);
					}
				}else{
					saveShare2userList(currentUser,clipEvent,null,null);
				}
			}else if(clipEvent.getCliptype()==4){
				saveUserfriendsMapping(clipEvent.getId(),clipEvent.getUid());
				clipEvent.setShareid(ToolsUtils.getUUID());
				this.clipEventDao.attachDirty(clipEvent);
			}
//			saveContactList(clipEvent,currentUser,contactlist,mobilelist,true);
			if(currentUser.getUsertype()==1)
				addClipEventClock(alerttime,clipEvent,mobilenotice);
			
			return clipEvent;
		}
	}
/*
	private void saveShareList(ClipEvent clipEvent, String sharelist) {
		List list=new ArrayList();
		if(sharelist.indexOf(",")>0){
			String[] groupids=sharelist.split(",");
			for (String sgroupid : groupids) {
				int groupid=Integer .parseInt(sgroupid);
				List templist=getContactIdsByGroupId(groupid);
				addContactList2List(templist,list);
			}
			
		}else{
			int groupid=Integer.parseInt(sharelist);
			if(groupid==0){
				Sharemapping sharemapping=new Sharemapping();
				sharemapping.setEventid(clipEvent.getId());
				sharemapping.setShare2uid(0);
				this.sharemappingDAO.save(sharemapping);
				saveUserfriendsMapping(clipEvent.getId(),clipEvent.getUid());
				clipEvent.setShareid(ToolsUtils.getUUID());
				clipEvent.setCliptype(3);
				this.clipEventDao.attachDirty(clipEvent);
				return;
			}
			list=getContactIdsByGroupId(groupid);
			
		}
		
		for (Object object : list) {
			int contactuid=(Integer)object;
			Sharemapping sharemapping=new Sharemapping();
			sharemapping.setEventid(clipEvent.getId());
			sharemapping.setShare2uid(contactuid);
			this.sharemappingDAO.save(sharemapping);
		}
		clipEvent.setShareid(ToolsUtils.getUUID());
		clipEvent.setCliptype(3);
		this.clipEventDao.attachDirty(clipEvent);
	}*/
	
	private void saveUserfriendsMapping(int eventid,int uid) {
		List list=this.contactDAO.findByQuery("from Contact c where c.uid=? and c.status=1", new Object[]{uid});
		if(list!=null&&list.size()>0){
			for (Object object : list) {
				Contact contact=(Contact) object;
				int contactuid=contact.getContactuid();
				Requestmapping requestmapping=new Requestmapping();
				requestmapping.setEventid(eventid);
				requestmapping.setShare2uid(contactuid);
				this.requestmappingDAO.save(requestmapping);
			}
		}
		
	}

	private void saveShare2userList(User currentUser,ClipEvent clipEvent, String share2userlist,String mobilelist) {
		List list=new ArrayList();
		clipEvent.setShareid(ToolsUtils.getUUID());
		clipEvent.setCliptype(3);
		this.clipEventDao.attachDirty(clipEvent);
		if(share2userlist!=null){
			if(share2userlist.indexOf(",")>0){
				String[] uids=share2userlist.split(",");
				for (String uid : uids) {
					int userid=Integer .parseInt(uid);
					list.add(userid);
				}
			}else{
				int userid=Integer.parseInt(share2userlist);
				list.add(userid);
			}
			for (Object object : list) {
				int contactuid=(Integer)object;
				Sharemapping sharemapping=new Sharemapping();
				sharemapping.setEventid(clipEvent.getId());
				sharemapping.setShare2uid(contactuid);
				int flag=this.isMobileNoticeUser(mobilelist, contactuid)?1:0;
				sharemapping.setMobilenotice(flag);
				this.sharemappingDAO.save(sharemapping);
				SystemMessage message=new SystemMessage();
				message.setEventid(clipEvent.getId());
				message.setFromuid(clipEvent.getUid());
				message.setMsgtime(Calendar.getInstance().getTimeInMillis());
				message.setMsgtype(SystemMessage.ADDTYPE);
				message.setUid(contactuid);
				message.setCheckstatus(0);
				sendInvitedEmail(currentUser.getName(), contactuid, clipEvent, 0);
				this.systemMessageDAO.save(message);
			}
		}else{
			//针对订阅商家的分享
			String contactSql="select c.uid from Contact c where c.contacttypeid=2 and c.status=1 and c.contactuid=?";
			list=this.contactDAO.findByQuery(contactSql, new Object[]{clipEvent.getUid()});
			Sharemapping sharemapping=new Sharemapping();
			sharemapping.setEventid(clipEvent.getId());
			sharemapping.setShare2uid(0);
			sharemapping.setMobilenotice(0);
			this.sharemappingDAO.save(sharemapping);
			for (Object object : list) {
				int subscribeduid=(Integer)object;
				SystemMessage message=new SystemMessage();
				message.setEventid(clipEvent.getId());
				message.setFromuid(clipEvent.getUid());
				message.setMsgtime(Calendar.getInstance().getTimeInMillis());
				message.setMsgtype(SystemMessage.ADDTYPE);
				message.setUid(subscribeduid);
				message.setCheckstatus(0);
				//推送给订阅用户
				this.systemMessageDAO.save(message);
			}
		}
		
	}
	
	private void addContactList2List(List fromList,List toList){
		for (Object object : fromList) {
			if(!toList.contains(object))
				toList.add(object);
		}
	}
	
	private List getContactIdsByGroupId(int groupid){
		return this.contactGroupMappingDAO.findByQuery("select map.contactuid from ContactGroupMapping map where map.groupid="+groupid);
	}

	private boolean checkUserHasMobile(Integer uid) {
		boolean flag=false;
		String query="from Usermobileinfo info where info.status=1 and info.uid="+uid;
		List list=this.usermobileinfoDAO.findByQuery(query);
		if(list!=null&&list.size()>0){
			flag=true;
		}
		return flag;
	}

	private void addClipEventClock(Long alerttime,ClipEvent clipEvent,int mobilenotice) {
		if(alerttime==null||alerttime==0l)
			return;
		Scheduler scheduler=null;
		try {
			scheduler = StdSchedulerFactory.getDefaultScheduler();
		} catch (SchedulerException e1) {
			e1.printStackTrace();
		}
		User user=userDAO.findById(clipEvent.getUid());
		List<UserEmail> userEmails=userEmailDAO.findByQuery("from UserEmail ue where ue.bindable=1 and ue.status=1 and ue.uid="+user.getId());
		Calendar now=Calendar.getInstance();
		Calendar calendar=Calendar.getInstance();
		calendar.setTimeInMillis(alerttime);
		int second=calendar.get(Calendar.SECOND);
		int min=calendar.get(Calendar.MINUTE);
		int hour=calendar.get(Calendar.HOUR_OF_DAY);
		int day=calendar.get(Calendar.DAY_OF_MONTH);
		int month=calendar.get(Calendar.MONTH);
		int year=calendar.get(Calendar.YEAR);
		String url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/clip_detail.html?eventid="+clipEvent.getId();
		if(now.get(Calendar.YEAR)==year&&now.get(Calendar.MONTH)==month&&now.get(Calendar.DAY_OF_MONTH)==day&&now.get(Calendar.HOUR_OF_DAY)==hour){
			int nowmin=now.get(Calendar.MINUTE);
			if(nowmin==min||nowmin+1==min){
				Map<String, Object> root = new HashMap<String, Object>();
				root.put("username", user.getName());
				root.put("url", url);
				String mailcontent = com.clip.util.FtlUtils.stringRender(root,"remindevent.ftl");
				for (UserEmail userEmail : userEmails) {
					SimpleMailSender.send(mailcontent, user.getName()+"，你有一个来自档期的消息", userEmail.getEmail());
				}
				if(mobilenotice==1){
					String query="from Usermobileinfo info where info.status=1 and info.uid="+user.getId();
					List list=this.usermobileinfoDAO.findByQuery(query);
					if(list!=null&&list.size()>0){
						Usermobileinfo usermobileinfo=(Usermobileinfo) list.get(0);
						MobileHttpSender.sendMobileMsg(usermobileinfo.getMobilenum(), MobileMsgPattern.getMobileClockMsg(user.getName(), clipEvent.getTitle()));
					}
				}
				return;
			}
		}
		String cronexp=""+second+" "+min+" "+hour+" "+day+" "+(month+1)+" ? "+year;
		
		CronTrigger trigger=null;
		JobBuilder jobBuilder= newJob(AlertJob.class).withIdentity("clipevent_"+clipEvent.getId());
		//"clipevent_"+clipEvent.getId(), Scheduler.DEFAULT_GROUP,AlertJob.class);
		JobDataMap map=new JobDataMap();
		map.put("title", clipEvent.getTitle());
		map.put("url", url);
		map.put("user", user);
		map.put("useremails", userEmails);
		List devicelist=this.userDevicetokenDAO.findByQuery("from UserDevicetoken token where token.uid="+user.getId());
		if(devicelist!=null&&devicelist.size()>0){
			UserDevicetoken devicetoken=(UserDevicetoken) devicelist.get(0);
			map.put("devicetoken", devicetoken.getDevicetoken());
		}else
			map.put("devicetoken", "");
		if(mobilenotice==1){
			String query="from Usermobileinfo info where info.status=1 and info.uid="+user.getId();
			List list=this.usermobileinfoDAO.findByQuery(query);
			if(list!=null&&list.size()>0){
				Usermobileinfo usermobileinfo=(Usermobileinfo) list.get(0);
				map.put("mobilenotice", 1);
				map.put("mobilenum", usermobileinfo.getMobilenum());
				map.put("title", clipEvent.getTitle());
			}else
				map.put("mobilenotice", 0);
		}else
			map.put("mobilenotice", 0);
		jobBuilder.usingJobData(map);
		JobDetail jobDetail =jobBuilder.build();
		try {
			trigger =newTrigger()
			.withIdentity("clipevent_"+clipEvent.getId())
			.withSchedule(cronSchedule(cronexp))
			.build();
			scheduler.scheduleJob(jobDetail, trigger);
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}   
	}


	public ClipEvent updateClipEvent(Integer eventid,Integer cliptype,String title, String address, String content,
			Long begintime, Long endtime, Long alerttime,Long deadlinetime,
			User currentUser, Calendar now,Integer status,int mobilenotice, String mobilelist,
			Integer iswholeday,String share2userlist) {
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		clipEvent.setTitle(title);
//		if(address!=null&&address.length()>0)clipEvent.setAddress(address);
		if(content!=null&&content.length()>0)clipEvent.setContent(content);
		clipEvent.setBegintime(begintime);
		clipEvent.setIswholeday(iswholeday);
		if(currentUser.getUsertype()==1){
			clipEvent.setEventtype(1);
		}else{
			clipEvent.setEventtype(2);
		}
		if(endtime==0l&&status!=0&&(cliptype==1||cliptype==3||cliptype==4)){
			Calendar calendar=Calendar.getInstance();
			calendar.setTimeInMillis(begintime);
			calendar.clear(Calendar.MILLISECOND);
			calendar.clear(Calendar.SECOND);
			calendar.clear(Calendar.MINUTE);
			calendar.set(Calendar.HOUR_OF_DAY,0);
			calendar.add(Calendar.DATE, 1);
			calendar.add(Calendar.MINUTE, -1);
			endtime=calendar.getTimeInMillis();
		}else{
			Calendar calendar=Calendar.getInstance();
			calendar.setTimeInMillis(endtime);
			calendar.clear(Calendar.MILLISECOND);
			calendar.clear(Calendar.SECOND);
			calendar.clear(Calendar.MINUTE);
			calendar.set(Calendar.HOUR_OF_DAY,0);
			calendar.add(Calendar.DATE, 1);
			calendar.add(Calendar.SECOND, -1);
			endtime=calendar.getTimeInMillis();
		}
		clipEvent.setEndtime(endtime);
		clipEvent.setUid(currentUser.getId());
		clipEvent.setCliptype(cliptype);
		clipEvent.setCreatetime(now.getTimeInMillis());
		if(clipEvent.getCliptype()==2){//不会发生
			clipEvent.setAlerttime(alerttime);
			this.clipEventDao.attachDirty(clipEvent);
			//addClipEventClock(alerttime, clipEvent);
			return clipEvent;
		}
		clipEvent.setReliedclip(0);
		clipEvent.setIsvip(0);
		clipEvent.setIsread(1);
		clipEvent.setStatus(status);
		clipEvent.setProcessstatus(0);
		if(status==0){
			clipEvent.setStatus(0);
			clipEvent.setAlerttime(0l);
//			clipEvent.setDeadlinetime(0l);
			clipEvent.setUpdatetime(now.getTimeInMillis());
			this.clipEventDao.attachDirty(clipEvent);
			if(clipEvent.getReliedclip()>0)
				removeContactList(clipEvent.getReliedclip(),currentUser.getId());
			else{
				removeContactListByEventId(clipEvent.getId());
			}
			return clipEvent;
		}else{
			clipEvent.setStatus(1);
			if(alerttime!=null&&alerttime>=0l)
				clipEvent.setAlerttime(alerttime);
//			if(deadlinetime!=null&&deadlinetime>0l)
//				clipEvent.setDeadlinetime(deadlinetime);
			clipEvent.setCreatetime(now.getTimeInMillis());
			clipEvent.setUpdatetime(0l);
			if(alerttime>0l){
				if(checkUserHasMobile(currentUser.getId())&&mobilenotice==1){
					clipEvent.setMobilenotice(mobilenotice);
				}
			}else{
				clipEvent.setMobilenotice(0);
			}
			this.clipEventDao.attachDirty(clipEvent);
			if(clipEvent.getCliptype()==3){
				if(share2userlist!=null&&share2userlist.length()>0){
					saveShare2userList(currentUser,clipEvent,share2userlist,mobilelist);
				}
			}else if(clipEvent.getCliptype()==4){
				saveUserfriendsMapping(clipEvent.getId(),clipEvent.getUid());
			}
			
//			saveContactList(clipEvent, currentUser, contactlist,mobilelist,true);
			addClipEventClock(alerttime, clipEvent,mobilenotice);
			
			return clipEvent;
		}
	}


	private void removeContactListByEventId(Integer id) {
		List<AlertUser> lists=this.alertUserDAO.findByEventid(id);
		if(lists!=null&&lists.size()>0){
			int listlength=lists.size();
			int count=0;
			for(AlertUser au:lists){
				if(au.getFolloweventid()==0){
					count++;
				}
			}
			if(listlength==count)
				this.alertUserDAO.excuteUpdateQuery("delete from AlertUser au where au.eventid="+id);
		}
	}

	private void removeContactList(Integer reliedclipid,Integer uid) {
		List<AlertUser> lists=this.alertUserDAO.findByEventid(reliedclipid);
		AlertUser currentAU=null;
		if(lists!=null&&lists.size()>0){
			int listlength=lists.size();
			int count=0;
			for(AlertUser au:lists){
				if(!au.getContactuid().equals(uid)&&au.getFolloweventid()==0){
					count++;
				}else if(au.getContactuid().equals(uid)){
					currentAU=au;
				}
			}
			ClipEvent clipEvent=this.clipEventDao.findById(reliedclipid);
			if(listlength==count&&clipEvent==null){
				this.alertUserDAO.excuteUpdateQuery("delete from AlertUser au where au.eventid="+reliedclipid);
				this.clipmessageDAO.excuteUpdateQuery("delete from Clipmessage msg where msg.eventid="+reliedclipid);
			}else{
				currentAU.setFolloweventid(0);
				currentAU.setStatus(2);
				this.alertUserDAO.attachDirty(currentAU);
			}
		}
	}




	public List<ClipEvent> loadclipsBeforeEndtime(Integer uid, Calendar now) {
		String query="from ClipEvent ce where ce.cliptype=1 and ce.uid="+uid+" and ce.endtime>="+now.getTimeInMillis()+" order by ce.createtime desc";
		return this.clipEventDao.findByQuery(query);
	}


	public List getEventsByDay(int year, int month, int day, Calendar now, User currentUser) {
		Calendar firstDateOfMonth=Calendar.getInstance();
		firstDateOfMonth.clear(Calendar.MILLISECOND);
		firstDateOfMonth.clear(Calendar.SECOND);
		firstDateOfMonth.clear(Calendar.MINUTE);
		firstDateOfMonth.set(Calendar.HOUR_OF_DAY,0);
		firstDateOfMonth.set(Calendar.YEAR, year);
		firstDateOfMonth.set(Calendar.MONTH, month);
		firstDateOfMonth.set(Calendar.DAY_OF_MONTH, day);
		Calendar lastDateOfMonth=(Calendar) firstDateOfMonth.clone();
		lastDateOfMonth.add(Calendar.DAY_OF_MONTH,+1);

		return getEventsByPassage(firstDateOfMonth,lastDateOfMonth, now, currentUser);
	}
	public List getEventsByMonth(int year, int month, Calendar now, User currentUser) {
		Calendar firstDateOfMonth=Calendar.getInstance();
		firstDateOfMonth.clear(Calendar.MILLISECOND);
		firstDateOfMonth.clear(Calendar.SECOND);
		firstDateOfMonth.clear(Calendar.MINUTE);
		firstDateOfMonth.set(Calendar.HOUR_OF_DAY, 0);
		firstDateOfMonth.set(Calendar.YEAR, year);
		firstDateOfMonth.set(Calendar.MONTH, month);
		firstDateOfMonth.set(Calendar.DAY_OF_MONTH, 1);
		Calendar lastDateOfMonth=(Calendar) firstDateOfMonth.clone();
		lastDateOfMonth.add(Calendar.MONTH,+1);
		return getEventsByPassage(firstDateOfMonth,lastDateOfMonth, now, currentUser);
	}
	public List getEventsByYear(int year,Calendar now, User currentUser){
		Calendar firstDateOfYear = Calendar.getInstance();
		firstDateOfYear.clear(Calendar.MILLISECOND);
		firstDateOfYear.clear(Calendar.SECOND);
		firstDateOfYear.clear(Calendar.MINUTE);
		firstDateOfYear.clear(Calendar.HOUR_OF_DAY);
		firstDateOfYear.clear(Calendar.MONTH);
		firstDateOfYear.set(Calendar.YEAR, year);
		Calendar lastDateOfYear = (Calendar) firstDateOfYear.clone();
		lastDateOfYear.add(Calendar.YEAR, 1);
		return getEventsByPassage(firstDateOfYear,lastDateOfYear, now, currentUser);
	}
	public List getEventsByWeek(int year, int numweek, Calendar now,
			User currentUser) {
		Map maps=new HashMap();
		Calendar firstDateOfWeek=Calendar.getInstance();
		firstDateOfWeek.clear(Calendar.MILLISECOND);
		firstDateOfWeek.clear(Calendar.SECOND);
		firstDateOfWeek.clear(Calendar.MINUTE);
		firstDateOfWeek.set(Calendar.HOUR_OF_DAY, 0);
		firstDateOfWeek.set(Calendar.YEAR, year);
		firstDateOfWeek.set(Calendar.WEEK_OF_YEAR,numweek);
		firstDateOfWeek.add(Calendar.DAY_OF_MONTH, Calendar.SUNDAY-firstDateOfWeek.get(Calendar.DAY_OF_WEEK));
		
		Calendar lastDateOfWeek=(Calendar) firstDateOfWeek.clone();
		lastDateOfWeek.add(Calendar.DAY_OF_MONTH, 7);
		
		return getEventsByPassage(firstDateOfWeek,lastDateOfWeek, now, currentUser);
	}

	/**
	 * eg:周日至周六
	 * 		[周日那天的00:00,下周日那天的00:00)
	 * 	         ∧							          ∧
	 * 		|								|
	 * 	      包含							     不包含
	 * */
	public List<EventForView> getEventsByPassage(Calendar startdate, Calendar enddate, Calendar now,
			User currentUser) {
		long begin=startdate.getTimeInMillis();
		long end=enddate.getTimeInMillis();
		
		String query1="from ClipEvent clip where (clip.cliptype=1 or clip.cliptype=3)  and clip.status=1 and clip.uid="+currentUser.getId()+" and " +
				"((clip.begintime<="+begin+" and clip.endtime>="+begin+") or "+
				" (clip.begintime>"+begin+" and clip.begintime<"+end+")) order by clip.createtime";
		//读取开始时间或者结束时间在今天内的事件，包括重复和非重复事件
		List<ClipEvent> clips=clipEventDao.findByQuery(query1);
		return assembleEventForViews(currentUser,clips,now);
	}

	
	
	public void updateOverDeadlinetime(ClipEvent clipEvent, Calendar now) {
//		if(clipEvent==null)
//			return;
//		if(clipEvent.getStatus()==0&&clipEvent.getReliedclip()==0)
//			return;
//		if(clipEvent.getProcessstatus()==2)
//			return;
//		if(clipEvent.getProcessstatus()==-1&&clipEvent.getBegintime()<=now.getTimeInMillis()){
//			clipEvent.setProcessstatus(0);
//			this.clipEventDao.attachDirty(clipEvent);
//			return;
//		}
//		if(clipEvent.getProcessstatus()==0&&clipEvent.getEndtime()<=now.getTimeInMillis()){
//			clipEvent.setProcessstatus(1);
//			this.clipEventDao.attachDirty(clipEvent);
//		}
	}

	public void updateProcessstatus(ShareEvent shareevent,Calendar now) {
		if(shareevent.getIswholeday()==1){
			Calendar temp=Calendar.getInstance();
			temp.setTimeInMillis(shareevent.getBegintime());
			temp.clear(Calendar.MILLISECOND);
			temp.clear(Calendar.SECOND);
			temp.clear(Calendar.MINUTE);
			temp.set(Calendar.HOUR_OF_DAY, 0);
			temp.add(Calendar.DATE, 1);
			if(now.getTimeInMillis()>=temp.getTimeInMillis()&&shareevent.getProcessstatus()==0){
				ClipEvent ce=this.clipEventDao.findById(shareevent.getEventid());
				ce.setProcessstatus(1);
				shareevent.setProcessstatus(1);
				this.clipEventDao.attachDirty(ce);
			}
		}else{
			if(now.getTimeInMillis()>shareevent.getEndtime()&&shareevent.getProcessstatus()==0){
				ClipEvent ce=this.clipEventDao.findById(shareevent.getEventid());
				ce.setProcessstatus(1);
				shareevent.setProcessstatus(1);
				this.clipEventDao.attachDirty(ce);
			}
		}
	}


	private boolean analyzeClipTime(Long begintime, Long endtime, Calendar now) {
		Calendar todaystart=(Calendar) now.clone();
		todaystart.clear(Calendar.MILLISECOND);
		todaystart.clear(Calendar.SECOND);
		todaystart.clear(Calendar.MINUTE);
		todaystart.set(Calendar.HOUR_OF_DAY, 0);
		
		Calendar tommorrowend=(Calendar) todaystart.clone();
		tommorrowend.add(Calendar.DATE, 2);
		
		if((begintime<=todaystart.getTimeInMillis()&&endtime>=todaystart.getTimeInMillis())||(begintime>todaystart.getTimeInMillis()&&begintime<tommorrowend.getTimeInMillis())){
			return true;
		}else{
			return false;
		}
	}




	public List<EventForView> getEventsByDay(Calendar startdate, Calendar now,
			User currentUser) {
		Calendar start=(Calendar) startdate.clone();
		
		start.clear(Calendar.MILLISECOND);
		start.clear(Calendar.SECOND);
		start.clear(Calendar.MINUTE);
		start.set(Calendar.HOUR_OF_DAY, 0);
		Calendar end=(Calendar) startdate.clone();
		end.add(Calendar.DAY_OF_MONTH, 1);
		return this.getEventsByPassage(start, end, now, currentUser);
	}

	
	private void analyzeClockTime(ClipEvent clipEvent,EventForView eventForView,Long starttime,Calendar now){
		Long clock=clipEvent.getAlerttime();
		Calendar calendar=Calendar.getInstance();
		calendar.setTimeInMillis(starttime);
		if(clock==0){
			eventForView.setClocked(true);
			return;
		}else{
			calendar.setTimeInMillis(clock);
			if(calendar.getTimeInMillis()<now.getTimeInMillis()){
				eventForView.setClocked(true);
			}else
				eventForView.setClocked(false);
		}
	}

	public List getTodayEvent(Calendar now, User currentUser) {
		return null;
	}

	public void addClock(User currentUser,Integer eventid, Long alerttime,int mobilenotice) {
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		if(clipEvent.getUid()!=currentUser.getId()&&clipEvent.getReliedclip()==0){
			//可能是感兴趣档期，找出ShareAcceptmapping
			String shareacceptmappingSQL="from ShareAcceptmapping map where map.eventid=? and map.uid=? and map.accepttype=1";
			List list=this.shareacceptmappingDAO.findByQuery(shareacceptmappingSQL, new Object[]{eventid,currentUser.getId()});
			if(list!=null&&list.size()==1){
				ShareAcceptmapping acceptmapping=(ShareAcceptmapping) list.get(0);
				int fleventid=acceptmapping.getFolloweventid();
				ClipEvent userClipEvent=this.clipEventDao.findById(fleventid);
				userClipEvent.setAlerttime(alerttime);
				userClipEvent.setMobilenotice(mobilenotice);
				this.clipEventDao.attachDirty(userClipEvent);
				addClipEventClock(alerttime, userClipEvent,mobilenotice);
			}
		}else if(clipEvent.getUid()==currentUser.getId()){
			clipEvent.setAlerttime(alerttime);
			clipEvent.setMobilenotice(mobilenotice);
			this.clipEventDao.attachDirty(clipEvent);
			addClipEventClock(alerttime, clipEvent,mobilenotice);
		}
	}

	public String app_AddClock(int uid,Integer eventid, Long alerttime) {
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent.getUid()!=uid){
			return "无权操作此档期";
		}else{
			clipEvent.setAlerttime(alerttime);
			this.clipEventDao.attachDirty(clipEvent);
			addClipEventClock(alerttime, clipEvent,0);
			return null;
		}
	}
	
	@Deprecated
	public List<ClipEvent> getEventsByYear(User currentUser, Integer year, int cliptype) {
		Calendar calendar=Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_YEAR, 1);
		calendar.set(Calendar.YEAR, year);
		calendar.clear(Calendar.MILLISECOND);
		calendar.clear(Calendar.SECOND);
		calendar.clear(Calendar.MINUTE);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		Calendar nextyear=(Calendar) calendar.clone();
		nextyear.add(Calendar.YEAR, 1);
		String query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.cliptype="+cliptype+" and ce.begintime>="+calendar.getTimeInMillis()+" and ce.begintime<"+nextyear.getTimeInMillis()+
			" order by ce.begintime";
		return this.clipEventDao.findByQuery(query);	
	}




	public void setEventImport(Integer isImport, Integer eventid) {
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		clipEvent.setIsvip(isImport);
		this.clipEventDao.attachDirty(clipEvent);
	}
	@Deprecated
	public List<EventForView> getEventsByLast24(User currentUser,Calendar now) {
		String query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and (ce.cliptype=1 or ce.cliptype=3) and ce.reliedclip>0 and ce.status=0 order by ce.createtime desc limit<24";
		List<ClipEvent> clips=clipEventDao.findByQuery(query);
		List<EventForView> re=assembleEventForViews(currentUser,clips,now);
		return re;
	}
	@Deprecated
	public List<EventForView> getEventsByUrgent24h(User currentUser, Calendar now) {
		Calendar calendar=(Calendar) now.clone();
		calendar.add(Calendar.HOUR_OF_DAY, 24);
		String query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.deadlinetime>"+now.getTimeInMillis()+" and ce.deadlinetime<="+calendar.getTimeInMillis()
			+" and ce.deadlinetime<>0 and (ce.cliptype=1 or ce.cliptype=3) and ce.reliedclip>0 and ce.status=0 order by ce.createtime desc";
		List<ClipEvent> clips=clipEventDao.findByQuery(query);
		List<EventForView> re=assembleEventForViews(currentUser,clips,now);
		return re;
	}
	
	public long countInvitedEvents(User currentUser, Calendar datetime) {
		Calendar start=(Calendar) datetime.clone();
		start.clear(Calendar.MILLISECOND);
		start.clear(Calendar.SECOND);
		start.clear(Calendar.MINUTE);
		start.set(Calendar.HOUR_OF_DAY, 0);
		Calendar end=(Calendar) datetime.clone();
		end.add(Calendar.DAY_OF_MONTH, 1);
		String query="select count(distinct se.eventid) from ShareEvent se where se.share2uid="+currentUser.getId()+" and se.reliedclip=0 " +
			"  and (( "+
			" se.begintime>="+start.getTimeInMillis()+" and se.begintime<"+end.getTimeInMillis()+
			" ) or ( "+
			" se.invitetime>0 and se.invitetime>="+start.getTimeInMillis()+" and se.invitetime<"+end.getTimeInMillis()+
			" ) ) ";
		return (Long)this.clipEventDao.getUniquerResult(query);
	}
	
//	public ClipEvent acceptInvitedClip(User currentUser, Integer eventid) {
//		ClipEvent clipEvent=getClipEventById(eventid);
//		clipEvent.setStatus(1);
//		clipEvent.setIsread(1);
//		this.clipEventDao.attachDirty(clipEvent);
//		AlertUser alertUser=(AlertUser) this.alertUserDAO.findByQuery("from AlertUser au where au.eventid="+clipEvent.getReliedclip()+" and au.contactuid="+clipEvent.getUid()).get(0);
//		alertUser.setStatus(1);
//		this.alertUserDAO.attachDirty(alertUser);
//		Calendar now=Calendar.getInstance();
//		if(clipEvent.getSeid()>0){
//			ShareAcceptmapping acceptmapping=new ShareAcceptmapping();
//			acceptmapping.setAccepttype(ShareAcceptmapping.JOINTYPE);
//			acceptmapping.setEventid(clipEvent.getSeid());
//			acceptmapping.setFolloweventid(eventid);
//			acceptmapping.setOpttime(now.getTimeInMillis());
//			acceptmapping.setUid(currentUser.getId());
//			this.shareacceptmappingDAO.save(acceptmapping);
//		}
//		if(checkIsExistClip(alertUser.getEventid()))
//			sendAcceptEmailToPublisher(alertUser.getUid(),currentUser.getName(),clipEvent.getReliedclip());
//		return clipEvent;
//	}
	
	private boolean checkIsExistClip(Integer eventid) {
		List list=this.clipEventDao.findByQuery("from ClipEvent ce where ce.id="+eventid+" and ce.status=1");
		if(list!=null&&list.size()>0)
			return true;
		else
			return false;
	}

	private void sendAcceptEmailToPublisher(Integer publisheruid, String fname, Integer eventid) {
		String url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/clip_detail.html?eventid="+eventid;
		User publisher=this.userDAO.findById(publisheruid);
		List<UserEmail> userEmails=userEmailDAO.findByQuery("from UserEmail ue where ue.bindable=1 and ue.status=1 and ue.uid="+publisheruid);
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("pname", publisher.getName());
		root.put("fname", fname);
		root.put("url", url);
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"acceptinvitedevent.ftl");
//		for (UserEmail userEmail : userEmails) {
//			SimpleMailSender.send(mailcontent, "档期网提醒", userEmail.getEmail());
//		}
	}

	private Integer getStartDayOfWeek(Long starttime,Calendar firstDateOfWeek){
		if(starttime<firstDateOfWeek.getTimeInMillis()){
			return 1;
		}else{
			Calendar calendar=Calendar.getInstance();
			calendar.setTimeInMillis(starttime);
			return calendar.get(Calendar.DAY_OF_WEEK);
		}
	}
	
	private Integer getEndDayOfWeek(Long endtime,Calendar lastDateOfWeek){
		if(endtime>lastDateOfWeek.getTimeInMillis()){
			return 7;
		}else{
			Calendar calendar=Calendar.getInstance();
			calendar.setTimeInMillis(endtime);
			return calendar.get(Calendar.DAY_OF_WEEK);
		}
	}
	
	private List<EventForView> assembleEventForViews(User currentUser,List<ClipEvent> clips,Calendar now){
		List<EventForView> returnlist=new ArrayList<EventForView>();
		for (ClipEvent clipEvent : clips) {
			Calendar calStart=Calendar.getInstance();
			calStart.setTimeInMillis(clipEvent.getBegintime());
			Calendar calEnd=Calendar.getInstance();
			calEnd.setTimeInMillis(clipEvent.getEndtime());
			EventForView eventForView=new EventForView();
			eventForView.setEventid(clipEvent.getId());
			eventForView.setUid(clipEvent.getUid());
//			eventForView.setFuid(clipEvent.getFuid());
			if(clipEvent.getReliedclip()>0){
				ClipEvent reliedclip=this.clipEventDao.findById(clipEvent.getReliedclip());
				if(reliedclip!=null&&reliedclip.getStatus()==1)
					eventForView.setPuid(reliedclip.getUid());
			}else
				eventForView.setPuid(clipEvent.getUid());
			eventForView.setCliptype(clipEvent.getCliptype());
			eventForView.setAddress(clipEvent.getAddress());
			eventForView.setContent(URLReplace.replace(clipEvent.getContent()));
			eventForView.setTitle(clipEvent.getTitle());
//			eventForView.setDeadlinetime(clipEvent.getDeadlinetime());
			updateOverDeadlinetime(clipEvent,now);
			eventForView.setProcessstatus(clipEvent.getProcessstatus());
			eventForView.setReliedclip(clipEvent.getReliedclip());
			eventForView.setIsvip(clipEvent.getIsvip());
			analyzeClockTime(clipEvent,eventForView,calStart.getTimeInMillis(),now);
			eventForView.setTodayOrTommorrow(analyzeClipTime(clipEvent.getBegintime(),clipEvent.getEndtime(),now));
			eventForView.setEventtype(ClipEvent.eventtypeInt2Str(clipEvent.getEventtype()));
			eventForView.setStarttime(calStart.getTimeInMillis());
			eventForView.setEndtime(calEnd.getTimeInMillis());
			eventForView.setIswholeday(clipEvent.getIswholeday());
			eventForView.setClocktime(clipEvent.getAlerttime());
			eventForView.setCreatetime(clipEvent.getCreatetime());
			eventForView.setUpdatetime(clipEvent.getUpdatetime());
//			List<String> list=getPublishname(clipEvent,currentUser);
//			if(list.size()>0){
//				eventForView.setPublishname(list.get(0));
//				if(list.size()>1)
//					eventForView.setForwardname(list.get(1));
//			}
			eventForView.setIsRead(clipEvent.getIsread());
			eventForView.setClipstatus(clipEvent.getStatus());
			returnlist.add(eventForView);
		}
		return returnlist;
	}

	/**
	 * @param clipEvent
	 * @param currentUser
	 * @return list 0	发起人
	 * 				1	转发人
	 * 			size 为0 说明原档期不存在或也被删除
	 */
//	public List<String> getPublishname(ClipEvent clipEvent,User currentUser){
//		List<String> returnList=new ArrayList<String>();
//		if(clipEvent.getReliedclip()>0){
//			if(clipEvent.getFuid()>0){
//				// 说明是分享档期保存为自己档期的档期
//				int relied=clipEvent.getReliedclip();
//				ClipEvent reliedEvent=this.clipEventDao.findById(relied);
//				if(reliedEvent!=null&&reliedEvent.getStatus()==1){
//					returnList.add(getUserName(currentUser.getId(),reliedEvent.getUid()));
//					returnList.add(getUserName(currentUser.getId(),clipEvent.getFuid()));
//				}
//			}else{
//				if(clipEvent.getCliptype()==3){
//					int relied=clipEvent.getReliedclip();
//					ClipEvent reliedEvent=this.clipEventDao.findById(relied);
//					returnList.add(getUserName(currentUser.getId(),reliedEvent.getUid()));
//				}else{
//					String temp="from AlertUser au where au.eventid="+clipEvent.getReliedclip()+" and au.contactuid="+clipEvent.getUid();
//					List list=this.alertUserDAO.findByQuery(temp);
//					if(list!=null&&list.size()>0){
//						AlertUser alertUser=(AlertUser) this.alertUserDAO.findByQuery(temp).get(0);
//						Contact contact=(Contact) this.contactDAO.findByQuery("from Contact c where c.uid="+currentUser.getId()+" and c.contactuid="+alertUser.getUid()).get(0);
//						returnList.add(contact.getName());
//					}
//				}
//			}
//		}else{
//			returnList.add(currentUser.getName());
//		}
//		return returnList;
//	}

	public void ignoreInvitedClip(Integer eventid){
		ClipEvent clipEvent=getClipEventById(eventid);
		clipEvent.setStatus(2);
		clipEvent.setIsread(1);
		clipEvent.setProcessstatus(2);
		this.clipEventDao.attachDirty(clipEvent);
		AlertUser alertUser=(AlertUser) this.alertUserDAO.findByQuery("from AlertUser au where au.eventid="+clipEvent.getReliedclip()+" and au.contactuid="+clipEvent.getUid()).get(0);
		alertUser.setStatus(3);
		this.alertUserDAO.attachDirty(alertUser);
	}

	public ClipEvent refuseInvitedClip(Integer eventid,User currentUser) throws ClipEventNotExistException{
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent.getReliedclip()==0||clipEvent.getUid()!=currentUser.getId()){
			return null;
		}
		if(clipEvent!=null&&clipEvent.getStatus()==1){
			int reliedclip=clipEvent.getReliedclip();
			ClipEvent rootEvent=null;
			if(clipEvent.getEventtype()==2&&clipEvent.getSeid()>0){
				rootEvent=this.getDetailClipEvent(clipEvent.getSeid());
				if(rootEvent==null||rootEvent.getStatus()!=1){
					throw new ClipEventNotExistException("");
				}
			}else{
				rootEvent=clipEvent;
			}
			List acceptlist=this.shareacceptmappingDAO.findByQuery("from ShareAcceptmapping map where map.accepttype=1 and map.eventid=? and map.uid=? and map.followeventid=?",new Object[]{rootEvent.getId(),currentUser.getId(),eventid});
			
			if(acceptlist!=null&&acceptlist.size()>0){
				ShareAcceptmapping shareAcceptmapping=(ShareAcceptmapping) acceptlist.get(0);
				this.shareacceptmappingDAO.delete(shareAcceptmapping);//delete shareacceptmapping
				
//				String sharemappingquery="delete from Sharemapping map where map.eventid="+userEvent.getId();
//				this.sharemappingDAO.excuteUpdateQuery(sharemappingquery);//delete sharemapping
				
				String picdelquery="delete from ClipeventPic pic where pic.eventid="+clipEvent.getId();
				this.clipeventPicDAO.excuteUpdateQuery(picdelquery);
				
				String addressdelquery="delete from ClipAddressref ref where ref.eventid="+clipEvent.getId();
				this.addressrefDAO.excuteUpdateQuery(addressdelquery);
				
				
				AlertUser alertUser=(AlertUser) this.alertUserDAO.findByQuery("from AlertUser au where au.eventid="+reliedclip+" and au.contactuid="+clipEvent.getUid()).get(0);
				alertUser.setStatus(2);
				sendRefuseEmailToPublisher(alertUser.getUid(),currentUser.getName(),clipEvent.getReliedclip());
				this.alertUserDAO.attachDirty(alertUser);
				
				
				this.clipEventDao.delete(clipEvent);
				removeQuartz("clipevent_"+clipEvent.getId());
				
				Calendar now=Calendar.getInstance();
				int addmsgeventid=0;
				if(clipEvent.getReliedclip()==0){
					addmsgeventid=clipEvent.getId();
				}else{
					addmsgeventid=clipEvent.getReliedclip();
				}
				if(clipEvent.getSeid()==0&&clipEvent.getEventtype()==2){
					addClipmessageEventMsg(addmsgeventid,currentUser.getId(),now,Clipmessage.QUITEVENTTYPE,reliedclip,false);
				}else{
					addClipmessageEventMsg(addmsgeventid,currentUser.getId(),now,Clipmessage.QUITEVENTTYPE,reliedclip,true);
				}
			}else{
				throw new ClipEventNotExistException("");
			}
		}else{
			throw new ClipEventNotExistException("");
		}
		
		//clipEvent.setProcessstatus(2);
//		this.clipEventDao.attachDirty(clipEvent);
//		AlertUser alertUser=(AlertUser) this.alertUserDAO.findByQuery("from AlertUser au where au.eventid="+clipEvent.getReliedclip()+" and au.contactuid="+clipEvent.getUid()).get(0);
//		alertUser.setStatus(2);
//		this.alertUserDAO.attachDirty(alertUser);
		
		return clipEvent;
	}
	private void sendRefuseEmailToPublisher(Integer publisheruid, String fname,
			Integer eventid) {
		String url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/clip_detail.html?eventid="+eventid;
		User publisher=this.userDAO.findById(publisheruid);
		List<UserEmail> userEmails=userEmailDAO.findByQuery("from UserEmail ue where ue.bindable=1 and ue.status=1 and ue.uid="+publisheruid);
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("pname", publisher.getName());
		root.put("fname", fname);
		root.put("url", url);
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"refuseinvitedevent.ftl");
//		for (UserEmail userEmail : userEmails) {
//			SimpleMailSender.send(mailcontent, "档期网提醒", userEmail.getEmail());
//		}
	}
	public static Integer PAGESIZE=15;
	/**
	 * @param queryby
	 * @param currentUser
	 * @param currentpage
	 * @param pagesize
	 * @param lastquerycreattime
	 * @param content
	 * @param dateTime
	 * @param orderby
	 * @param isDesc
	 * @return
	 */
	public List queryClipList(String queryby, User currentUser,Integer currentpage,int pagesize,Long lastquerycreattime,
			String content,Calendar dateTime,String orderby,boolean isDesc) {
		StringBuffer query=new StringBuffer();
		boolean hasTime=false;
		boolean hasSearchContent=false;
		String clipeventtimequery=null;
		if(dateTime!=null){
			hasTime=true;
			Calendar firstDate=(Calendar) dateTime.clone();
			Calendar secondDate=(Calendar) firstDate.clone();
			secondDate.add(Calendar.DATE, 1);
			clipeventtimequery=" (( ce.begintime<="+firstDate.getTimeInMillis()+" and ce.endtime>="+firstDate.getTimeInMillis()+" ) or  ( ce.begintime>"+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis()+" )) ";
		}
		if(content!=null&&content.trim().length()>0){
			hasSearchContent=true;
		}
		if(queryby.equals("own")){
			query.append("from ClipEvent ce where ce.uid="+currentUser.getId()+" and (ce.cliptype=4 or ce.cliptype=3) and ce.status=1 ");
			if(hasTime){
				Calendar firstDate=(Calendar) dateTime.clone();
				Calendar secondDate=(Calendar) firstDate.clone();
				secondDate.add(Calendar.DATE, 1);
				query.append(" and ( ");
				query.append(clipeventtimequery);
				query.append("  or ( ");
				query.append(" ce.invitetime>0 and ce.invitetime>="+firstDate.getTimeInMillis()+" and ce.invitetime<"+secondDate.getTimeInMillis());
				query.append(" )) ");
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
			if(lastquerycreattime>0l){
				query.append(" and ce.createtime<=");
				query.append(lastquerycreattime);
			}
			if(orderby!=null){
				query.append(" order by ce."+orderby);
				if(isDesc){
					query.append(" desc");
				}
				query.append(", ce.id desc");
			}else{
				query.append(" order by ce.createtime desc, ce.id desc");
			}
			List list=this.clipEventDao.pagingByQuery(query.toString(),currentpage,pagesize);
			return list;
		}else if(queryby.equals("private")){
			query.append("from ClipEvent ce where ce.cliptype=1 ");
			query.append(" and ce.uid=");
			query.append(currentUser.getId());
			if(hasTime){
				query.append(" and ");
				query.append(clipeventtimequery);
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
			if(lastquerycreattime>0l){
				query.append(" and ce.createtime<=");
				query.append(lastquerycreattime);
			}
			if(orderby!=null){
				query.append(" order by ce."+orderby);
				if(isDesc){
					query.append(" desc");
				}
				query.append(", ce.id desc");
			}else{
				query.append(" order by ce.createtime desc, ce.id desc");
			}
			
			List list=this.clipEventDao.pagingByQuery(query.toString(),currentpage,pagesize);
			return list;
		}else if(queryby.equals("share")){
			query.append("from RequestEvent ce where ce.share2uid="+currentUser.getId()+" ");
			if(hasTime){
				query.append(" and ");
				query.append(clipeventtimequery);
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
			if(lastquerycreattime>0l){
				query.append(" and ce.createtime<=");
				query.append(lastquerycreattime);
			}
			if(orderby!=null){
				query.append(" order by ce."+orderby);
				if(isDesc){
					query.append(" desc");
				}
				query.append(", ce.id desc");
			}else{
				query.append(" order by ce.createtime desc, ce.id desc");
			}
			
			
			List list=this.clipEventDao.pagingByQuery(query.toString(),currentpage,pagesize);
			return list;
		}else if(queryby.equals("memo")){ 
			query.append("from ClipEvent clip where clip.cliptype=2 and clip.status=1 and clip.uid="+currentUser.getId());
			if(dateTime!=null){
				SimpleDateFormat dateFormat=new SimpleDateFormat("MMdd");
				Calendar firstDate=(Calendar) dateTime.clone();
				Calendar secondDate=(Calendar) firstDate.clone();
				secondDate.add(Calendar.DATE, 1);
				query.append(" and clip.begintime<"+secondDate.getTimeInMillis());
				query.append(" and clip.endtime=1"+dateFormat.format(firstDate.getTime()));
			}
			if(hasSearchContent)
				query.append(" and clip.title like '%"+content+"%' ");
			query.append(" order by clip.createtime desc,clip.id desc");
		}else if(queryby.equals("invite")){
			
			query.append("from ShareEvent ce where ce.share2uid="+currentUser.getId());
			query.append(" and ce.reliedclip=0 ");
//			query.append(" and ce.acceptstatus=1 ");
			if(hasTime){
				Calendar firstDate=(Calendar) dateTime.clone();
				Calendar secondDate=(Calendar) firstDate.clone();
				secondDate.add(Calendar.DATE, 1);
				query.append(" and ( ");
				query.append(" ce.begintime>="+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis());
				query.append("  or ( ");
				query.append(" ce.invitetime>0 and ce.invitetime>="+firstDate.getTimeInMillis()+" and ce.invitetime<"+secondDate.getTimeInMillis());
				query.append(" )) ");
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
			query.append(" order by ce.createtime desc,ce.id desc");
		}else if(queryby.equals("alert")){
			query.append("from ClipEvent ce where ce.uid="+currentUser.getId());
			if(hasTime){
				Calendar firstDate=(Calendar) dateTime.clone();
				Calendar secondDate=(Calendar) firstDate.clone();
				secondDate.add(Calendar.DATE, 1);
				query.append(" and ce.alerttime>="+firstDate.getTimeInMillis()+" and ce.alerttime<"+secondDate.getTimeInMillis());
			}else{
				query.append(" and ce.alerttime>0");
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
			query.append(" order by ce.createtime desc,ce.id desc");
		}else if(queryby.equals("cache")){
			query.append("from ClipEvent ce where ce.reliedclip=0 and ce.uid="+currentUser.getId());
			query.append(" and ce.status=0");
			query.append(" order by ce.updatetime desc");
		}else if(queryby.equals("recycle")){
			query.append("from ClipEvent ce where ce.uid="+currentUser.getId());
			query.append(" and ce.status=2");
			query.append(" order by ce.createtime desc,ce.id desc");
		}else if(queryby.equals("search")){
			query.append(" from ClipEvent ce where ce.reliedclip=0 and ce.status=1 ");
			query.append(" and (ce.uid="+currentUser.getId());
			query.append(" or (ce.eventtype=2 and ce.seid=0)");
			query.append(" or exists( select sh.id from Sharemapping sh where sh.eventid=ce.id and sh.share2uid="+currentUser.getId()+")");
			query.append(" or exists( select re.id from Requestmapping re where re.eventid=ce.id and re.share2uid="+currentUser.getId()+")");
			query.append(" ) ");
//			if(hasSearchContent)
			query.append(" and ce.title like '%"+content+"%' ");
			query.append(" order by ce.createtime desc,ce.id desc");
		}
		if(pagesize==0){
			List list=this.clipEventDao.findByQuery(query.toString());
			return list;
		}else{
			List list=this.clipEventDao.pagingByQuery(query.toString(),currentpage,this.PAGESIZE);
			return list;
		}
	}

	public Long queryClipListTotalCount(String queryby, User currentUser,String content,Calendar dateTime) {
		StringBuffer query=new StringBuffer();
		boolean hasTime=false;
		boolean hasSearchContent=false;
		String clipeventtimequery=null;
		String shareventtimequery=null;
		Calendar firstDate=null;
		Calendar secondDate=null;
		if(dateTime!=null){
			firstDate=(Calendar) dateTime.clone();
			secondDate=(Calendar) firstDate.clone();
			secondDate.add(Calendar.DATE, 1);
			hasTime=true;
			clipeventtimequery=" (( ce.begintime<="+firstDate.getTimeInMillis()+" and ce.endtime>="+firstDate.getTimeInMillis()+" ) or  ( ce.begintime>"+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis()+" )) ";
			shareventtimequery=" ((s.begintime<="+firstDate.getTimeInMillis()+" and s.endtime>="+firstDate.getTimeInMillis()+") or (s.begintime>"+firstDate.getTimeInMillis()+" and s.begintime<"+secondDate.getTimeInMillis()+" )) ";
		}
		if(content!=null){
			hasSearchContent=true;
		}
		if(queryby.equals("own")){
			query.append("select count(*) from ClipEvent ce where ce.uid="+currentUser.getId()+" and (ce.cliptype=4 or ce.cliptype=3) and ce.status=1 ");
			if(hasTime){
				query.append(" and (");
				query.append(clipeventtimequery);
				query.append("  or ( ");
				query.append(" ce.invitetime>0 and ce.invitetime>="+firstDate.getTimeInMillis()+" and ce.invitetime<"+secondDate.getTimeInMillis());
				query.append(" ))");
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
		}else if(queryby.equals("private")){
			query.append("select count(*) from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.cliptype=1 and ce.status=1 ");
			if(hasTime){
				query.append(" and ");
				query.append(clipeventtimequery);
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
		}else if(queryby.equals("share")){
			query.append(" (s.share2uid="+currentUser.getId()+" or exists(SELECT c.id FROM contact c where c.contactuid=");
			query.append(currentUser.getId());
			query.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0)) ");
			if(hasTime){
				query.append(" and ");
				query.append(shareventtimequery);
			}
			if(hasSearchContent)
				query.append(" and s.title like '%"+content+"%' ");
			return this.clipEventDao.countByNamedQuery("countShareEvents", new Object[]{query.toString()});
		}else if(queryby.equals("memo")){ 
			query.append("select count(*) from ClipEvent clip where clip.cliptype=2 and clip.status=1 and clip.uid="+currentUser.getId());
			if(dateTime!=null){
				SimpleDateFormat dateFormat=new SimpleDateFormat("MMdd");
				query.append(" and clip.begintime<"+secondDate.getTimeInMillis());
				query.append(" and clip.endtime=1"+dateFormat.format(firstDate.getTime()));
			}
			if(hasSearchContent)
				query.append(" and clip.title like '%"+content+"%' ");
			
		}else if(queryby.equals("invite")){
			query.append(" select count(distinct ce.eventid) from ShareEvent ce where ce.share2uid="+currentUser.getId());
			if(hasTime){
				query.append(" and ((");
				query.append(" ce.begintime>="+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis());
				query.append("  ) or ( ");
				query.append(" ce.invitetime>0 and ce.invitetime>="+firstDate.getTimeInMillis()+" and ce.invitetime<"+secondDate.getTimeInMillis());
				query.append(" ))"); 
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
			
		}else if(queryby.equals("alert")){
			query.append("select count(*) from ClipEvent ce where ce.uid="+currentUser.getId());
			if(hasTime){
				query.append(" and ce.alerttime>="+firstDate.getTimeInMillis()+" and ce.alerttime<"+secondDate.getTimeInMillis());
			}else{
				query.append(" and ce.alerttime>0");
			}
			if(hasSearchContent)
				query.append(" and ce.title like '%"+content+"%' ");
		}else if(queryby.equals("cache")){
			query.append("select count(*) from ClipEvent ce where ce.reliedclip=0 and ce.uid="+currentUser.getId());
			query.append(" and ce.status=0");
		}else if(queryby.equals("recycle")){
			query.append("select count(*) from ClipEvent ce where ce.uid="+currentUser.getId());
			query.append(" and ce.status=2");
		}else if(queryby.equals("search")){
			query.append(" select count(*) from ClipEvent ce where ce.reliedclip=0 and ce.status=1 ");
			query.append(" and (ce.uid="+currentUser.getId());
			query.append(" or (ce.eventtype=2 and ce.seid=0)");
			query.append(" or exists( select sh.id from Sharemapping sh where sh.eventid=ce.id and sh.share2uid="+currentUser.getId()+")");
			query.append(" or exists( select re.id from Requestmapping re where re.eventid=ce.id and re.share2uid="+currentUser.getId()+")");
			query.append(" ) ");
			query.append(" and ce.title like '%"+content+"%' ");
		}
		return (Long)this.clipEventDao.findByQuery(query.toString()).get(0);
	}

	public Integer queryClipListPageCount(Long totalcount) {
		BigDecimal br = new BigDecimal(totalcount).divide(new BigDecimal(PAGESIZE),BigDecimal.ROUND_UP);
		Integer pageCount = (br.doubleValue()<1&&br.doubleValue()>=0 ? 1 : br.intValue());
		return pageCount;
	}
	
	/**
	 * @param eventid
	 * @param currentUser 
	 * @return key: index
	 * 		   value:[contactuid,name,email,status]
	 */
	public Map<Integer,List> getClipInvitedPerson(Integer eventid, User currentUser) {
		List<AlertUser> list=this.alertUserDAO.findByEventid(eventid);
		Map<Integer,List> map=new HashMap<Integer, List>();
		for (int i = 0; i < list.size(); i++) {
			AlertUser alertUser=list.get(i);
			Contact contact=this.contactDAO.findById(alertUser.getContactid());
			List tmp=new ArrayList();
			if(contact==null){
				tmp.add(0);
				tmp.add("未知");
				tmp.add("未知email");
				tmp.add(0);
			}else{
				int contactuid=contact.getContactuid();
				tmp.add(contactuid);
				User user=this.userDAO.findById(contactuid);
				if(contactuid==currentUser.getId()){
					tmp.add(user.getName());
					tmp.add(contact.getContactemail());
					tmp.add(alertUser.getStatus());
					tmp.add(user.getName());
				}else{
					List temp=this.contactDAO.findByQuery("from Contact c where c.uid="+currentUser.getId()+" and c.contactuid="+contactuid);
					if(temp!=null&&temp.size()>0){
						Contact curContact=(Contact) temp.get(0);
						tmp.add(curContact.getName());
						tmp.add(curContact.getContactemail());
					}else{
						tmp.add(user.getName());
						tmp.add(user.getEmail());
					}
					tmp.add(alertUser.getStatus());
					tmp.add(user.getName());
				}
			}
			
			map.put((i+1), tmp);
		}
		return map;
	}

	public Long queryCacheClipListTotalCount(User currentUser) {
		String query=null;
		query="select count(*) from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.status=0 and ce.reliedclip=0 ";
		query+=" and (ce.cliptype=1 or ce.cliptype=3) ";
		return (Long)this.clipEventDao.findByQuery(query).get(0);
	}

	public List<EventForView> queryCacheClipList(User currentUser, Integer currentpage) {
		String query=null;
		query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.status=0 and ce.reliedclip=0 ";
		query+=" and (ce.cliptype=1 or ce.cliptype=3) ";
		query+=" order by ce.updatetime desc";
		List<ClipEvent> list=this.clipEventDao.pagingByQuery(query,currentpage,this.PAGESIZE);
		Calendar calendar=Calendar.getInstance();
		return assembleEventForViews(currentUser,list,calendar);
	}

	public void deletePatchCacheEvents(User currentUser, String eventids) {
		this.clipEventDao.updateByQuery("delete from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.id in ("+eventids+")");
	}

	public Long queryRemindClipListTotalCount(User currentUser,Integer year,Integer month,Integer date) {
		String query=null;
		if(year==0&&month==0&&date==0){
			query="select count(*) from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.alerttime>0 and ((ce.status=0 and ce.reliedclip>0) or ce.status=1) ";
			query+=" and (ce.cliptype=1 or ce.cliptype=3) ";
		}else{
			Calendar daystart=Calendar.getInstance();
			daystart.clear(Calendar.MILLISECOND);
			daystart.clear(Calendar.SECOND);
			daystart.clear(Calendar.MINUTE);
			daystart.set(Calendar.HOUR_OF_DAY, 0);
			daystart.set(Calendar.YEAR, year);
			daystart.set(Calendar.MONTH, month);
			daystart.set(Calendar.DAY_OF_MONTH, date);
			Calendar dayend=(Calendar) daystart.clone();
			dayend.add(Calendar.DATE, 1);
			query="select count(*) from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.alerttime>0 and ((ce.status=0 and ce.reliedclip>0) or ce.status=1) ";
			query+=" and ce.alerttime>="+daystart.getTimeInMillis()+" and ce.alerttime<"+dayend.getTimeInMillis();
			query+=" and (ce.cliptype=1 or ce.cliptype=3) ";
		}
		return (Long)this.clipEventDao.findByQuery(query).get(0);
	}

	public List<EventForView> queryRemindClipList(User currentUser, Integer currentpage,Integer year,Integer month,Integer date) {
		String query=null;
		if(year==0&&month==0&&date==0){
			query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.alerttime>0 and ((ce.status=0 and ce.reliedclip>0) or ce.status=1) ";
			query+=" and (ce.cliptype=1 or ce.cliptype=3) ";
			query+=" order by ce.alerttime desc";
		}else{
			Calendar daystart=Calendar.getInstance();
			daystart.clear(Calendar.MILLISECOND);
			daystart.clear(Calendar.SECOND);
			daystart.clear(Calendar.MINUTE);
			daystart.set(Calendar.HOUR_OF_DAY, 0);
			daystart.set(Calendar.YEAR, year);
			daystart.set(Calendar.MONTH, month);
			daystart.set(Calendar.DAY_OF_MONTH, date);
			Calendar dayend=(Calendar) daystart.clone();
			dayend.add(Calendar.DATE, 1);
			query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.alerttime>0 and ((ce.status=0 and ce.reliedclip>0) or ce.status=1) ";
			query+=" and ce.alerttime>="+daystart.getTimeInMillis()+" and ce.alerttime<"+dayend.getTimeInMillis();
			query+=" and (ce.cliptype=1 or ce.cliptype=3) ";
			query+=" order by ce.alerttime desc";
		}
		List<ClipEvent> list=this.clipEventDao.pagingByQuery(query,currentpage,this.PAGESIZE);
		Calendar calendar=Calendar.getInstance();
		return assembleEventForViews(currentUser,list,calendar);
	}

	public Long queryRecycleClipListTotalCount(User currentUser) {
		String query=null;
		query="select count(*) from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.status=2 ";
		query+=" and (ce.cliptype=1 or ce.cliptype=3) ";
		return (Long)this.clipEventDao.findByQuery(query).get(0);
	}

	public List<EventForView> queryRecycleClipList(User currentUser, Integer currentpage) {
		String query=null;
		query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.status=2 ";
		query+=" and (ce.cliptype=1 or ce.cliptype=3) ";
		query+=" order by ce.createtime desc";
		List<ClipEvent> list=this.clipEventDao.pagingByQuery(query,currentpage,this.PAGESIZE);
		Calendar calendar=Calendar.getInstance();
		return assembleEventForViews(currentUser,list,calendar);
	}

	public List getEventsByAlertDay(Calendar startdate, User currentUser,boolean isShortQuery) {
		Calendar start=(Calendar) startdate.clone();
		start.clear(Calendar.MILLISECOND);
		start.clear(Calendar.SECOND);
		start.clear(Calendar.MINUTE);
		start.set(Calendar.HOUR_OF_DAY, 0);
		Calendar end=(Calendar) startdate.clone();
		end.add(Calendar.DAY_OF_MONTH, 1);
		String query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.alerttime>="+start.getTimeInMillis()+" and ce.alerttime<"+end.getTimeInMillis()+" order by ce.alerttime";
		if(isShortQuery)
			return this.clipEventDao.pagingByQuery(query,0,6);
		else
			return this.clipEventDao.findByQuery(query);
	}

	public int getEventsByAlertDayOnlyCount(Calendar startdate,
			User currentUser) {
		Calendar start=(Calendar) startdate.clone();
		start.clear(Calendar.MILLISECOND);
		start.clear(Calendar.SECOND);
		start.clear(Calendar.MINUTE);
		start.set(Calendar.HOUR_OF_DAY, 0);
		Calendar end=(Calendar) startdate.clone();
		end.add(Calendar.DAY_OF_MONTH, 1);
		String query="select count(*) from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.alerttime>="+start.getTimeInMillis()+" and ce.alerttime<"+end.getTimeInMillis()+" order by ce.alerttime";
		return this.clipEventDao.countByQuery(query);
	}

	public String replyMessage(int eventid,String content,User currentUser,Calendar now){
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent!=null){
			int noticeeventid=0;
			boolean isCCclip=false;//表示评论的档期是商家的档期
			ClipEvent reliedclip=null;
			if(clipEvent.getReliedclip()>0){
				reliedclip=this.getDetailClipEvent(clipEvent.getReliedclip());
				if(reliedclip==null){
					return "回复的档期不存在";
				}else{
					if(reliedclip.getEventtype()==2&&reliedclip.getSeid()==0){
						isCCclip=true;
					}
					noticeeventid=reliedclip.getId();
				}
			}else{
				noticeeventid=clipEvent.getId();
			}
			Clipmessage clipmessage=new Clipmessage();
			clipmessage.setContent(content);
			if(clipEvent.getReliedclip()==0)
				clipmessage.setEventid(eventid);
			else
				clipmessage.setEventid(clipEvent.getReliedclip());
			clipmessage.setReplytime(now.getTimeInMillis());
			clipmessage.setUid(currentUser.getId());
			clipmessage.setMsgtype(0);
			this.clipmessageDAO.save(clipmessage);
			if(isCCclip)
				return null;
			String sharemappingSQL="from Sharemapping map where map.eventid="+noticeeventid+" and map.acceptstatus=1";
			List list=this.sharemappingDAO.findByQuery(sharemappingSQL);
			if(list!=null&&list.size()>0){
				for (Object object : list) {
					Sharemapping sharemapping=(Sharemapping) object;
					int share2uid=sharemapping.getShare2uid();
					if(currentUser.getId()!=share2uid){
						MsgNotice msgNotice=new MsgNotice();
						msgNotice.setEventid(noticeeventid);
						msgNotice.setCheckstatus(0);
						msgNotice.setMsgid(clipmessage.getId());
						msgNotice.setUid(share2uid);
						msgNotice.setMsgtime(now.getTimeInMillis());
						this.msgNoticeDAO.save(msgNotice);
					}
				}
			}
			if(reliedclip==null){
				if(clipEvent.getUid()!=currentUser.getId()){
					MsgNotice msgNotice=new MsgNotice();
					msgNotice.setEventid(noticeeventid);
					msgNotice.setCheckstatus(0);
					msgNotice.setMsgid(clipmessage.getId());
					msgNotice.setUid(clipEvent.getUid());
					msgNotice.setMsgtime(now.getTimeInMillis());
					this.msgNoticeDAO.save(msgNotice);
				}
			}else{
				if(reliedclip.getUid()!=currentUser.getId()){
					MsgNotice msgNotice=new MsgNotice();
					msgNotice.setEventid(noticeeventid);
					msgNotice.setCheckstatus(0);
					msgNotice.setMsgid(clipmessage.getId());
					msgNotice.setUid(reliedclip.getUid());
					msgNotice.setMsgtime(now.getTimeInMillis());
					this.msgNoticeDAO.save(msgNotice);
				}
			}
			return null;
		}else{
			return "回复的档期不存在";
		}
	}

	public List<Clipmessage> loadAllMessageByEventid(Integer eventid) {
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		if(clipEvent!=null){
			List<Clipmessage> list=null;
			list=this.clipmessageDAO.findByEventid(eventid);
			return list;
		}else
			return null;
	}

	public List<Clipmessage> loadPagingMessageByEventid(Integer eventid,int currentpage,int pagelength) {
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		int dealeventid=0;
		if(clipEvent.getReliedclip()==0){
			dealeventid=clipEvent.getId();
		}else{
			dealeventid=clipEvent.getReliedclip();
		}
		String query="from Clipmessage msg where msg.eventid=? order by msg.replytime desc";
		return this.clipmessageDAO.pagingByQuery(query,currentpage,pagelength,new Object[]{dealeventid});
	}
	
	public List getMemoEventsByDay(Calendar startdate, Calendar now,
			User currentUser) {
		SimpleDateFormat dateFormat=new SimpleDateFormat("MMdd");
		Calendar date=(Calendar) startdate.clone();
		date.add(Calendar.DATE, 1);
		String query1="from ClipEvent clip where clip.cliptype=2 and clip.status=1 and clip.uid="+currentUser.getId()
			+" and clip.begintime<"+date.getTimeInMillis()
			+" and clip.endtime="+"1"+dateFormat.format(startdate.getTime())+" order by clip.createtime";
		List<ClipEvent> clips=clipEventDao.findByQuery(query1);
		return assembleEventForViews(currentUser,clips,now);
	}

	public int countMemoEventsByDay(Calendar startdate,User currentUser) {
		String query1="select count(*) from ClipEvent clip where clip.cliptype=2 and clip.status=1 and clip.uid="+currentUser.getId();
		if(startdate!=null){
			SimpleDateFormat dateFormat=new SimpleDateFormat("MMdd");
			Calendar date=(Calendar) startdate.clone();
			date.add(Calendar.DATE, 1);
			query1+=" and clip.begintime<"+date.getTimeInMillis()
					+" and clip.endtime="+"1"+dateFormat.format(startdate.getTime());
		}
		return clipEventDao.countByQuery(query1);
	}

	
	
	public List getMemoEvents(Calendar now,User currentUser, Integer currentpage) {
		int month=now.get(Calendar.MONTH)+1;
		Calendar nextyear=(Calendar) now.clone();
		nextyear.add(Calendar.YEAR, 1);
		nextyear.add(Calendar.MONTH, -1);
		String str=month<10?"0"+month:""+month;
		Long temp=Long.parseLong("1"+str+"01");
		String query="(select * from (select clip1.id,clip1.title,clip1.begintime,clip1.endtime,clip1.alerttime from ClipEvent clip1 " +
				" where clip1.cliptype=2 and clip1.clipstatus=1 " +
				" and clip1.uid="+currentUser.getId()+
				" and clip1.begintime<="+nextyear.getTimeInMillis()+
				" and clip1.endtime>="+temp+
				" order by clip1.endtime"+
				" ) as AA)"+
				" union all"+
				" (select * from(select clip2.id,clip2.title,clip2.begintime,clip2.endtime,clip2.alerttime from ClipEvent clip2 " +
				" where clip2.cliptype=2 and clip2.clipstatus=1 " +
				" and clip2.uid="+currentUser.getId()+
				" and clip2.begintime<="+nextyear.getTimeInMillis()+
				" and clip2.endtime<"+temp+
				" order by clip2.endtime"+
				" ) as BB) ";
		List list=this.clipEventDao.pagingBySqlQuery(query,currentpage,this.MEMOPERPAGE);
		List re=new ArrayList();
		for (Object object : list) {
			Object [] objs=(Object[]) object;
			ClipEvent clipEvent=new ClipEvent();
			//id1 begintime6 alerttime9 title3
			clipEvent.setId((Integer)objs[0]);
			clipEvent.setTitle((String)objs[1]);
			BigInteger bBegintime=(BigInteger) objs[2];
			clipEvent.setBegintime(bBegintime.longValue());
			BigInteger bAlerttime=(BigInteger) objs[4];
			clipEvent.setAlerttime(bAlerttime.longValue());
			re.add(clipEvent);
		}
		return re;
	}

	public String updateMemoContent(Integer eventid, String title,long alerttime,int mobilenotice,
			User currentUser) {
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		if(clipEvent!=null&&clipEvent.getCliptype()==2&&clipEvent.getUid()==currentUser.getId()){
			if(title.length()>50){
				return "数据错误";
			}else{
				clipEvent.setTitle(title);
				clipEvent.setAlerttime(alerttime);
				clipEvent.setMobilenotice(mobilenotice);
				if(alerttime==0l)
					removeQuartz("clipevent_"+clipEvent.getId());
				else if(alerttime>0l){
					removeQuartz("clipevent_"+clipEvent.getId());
					addClipEventClock(alerttime,clipEvent,mobilenotice);
				}
				this.clipEventDao.attachDirty(clipEvent);
				return "";
			}
		}else{
			return "数据错误";
		}
	}

	public Long countShareEventsByDay(Calendar startdate, User currentUser,
			int contacttype) {
		
		Calendar enddate=(Calendar) startdate.clone();
		enddate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer("select count(*) from shareevent s where ");
		query.append(" ((s.begintime<="+startdate.getTimeInMillis()+" and s.endtime>="+startdate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+startdate.getTimeInMillis()+" and s.begintime<"+enddate.getTimeInMillis()+"))");
		query.append(" and ");
		if(contacttype==1){
			query.append(" (s.share2uid="+currentUser.getId()+" or exists(SELECT c.id FROM Contact c where c.contactuid=");
			query.append(currentUser.getId());
			query.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0))");
		}else
			query.append(" s.share2uid=0");
		List list=this.clipEventDao.findBySqlQuery(query.toString());
		if(list!=null&&list.size()>0){
			BigInteger count=(BigInteger ) list.get(0);
			return count.longValue();
		}else
			return 0l;
		
	}
	
	public long countStartedShareEventsByDay(Calendar startdate,
			User currentUser, int contacttype) {
		Calendar enddate=(Calendar) startdate.clone();
		enddate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer();
		query.append("select count(distinct re.eventid) from RequestEvent re where re.share2uid=");
		query.append(currentUser.getId());
		query.append(" and ((re.begintime<="+startdate.getTimeInMillis()+" and re.endtime>="+startdate.getTimeInMillis()+") or ");
		query.append(" (re.begintime>"+startdate.getTimeInMillis()+" and re.begintime<"+enddate.getTimeInMillis()+"))");
		return (Long)this.clipEventDao.getUniquerResult(query.toString());
	}
	
	public long countEndedShareEventsByDay(Calendar startdate,
			User currentUser, int contacttype) {
		Calendar enddate=(Calendar) startdate.clone();
		enddate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer();
		query.append("select count(distinct re.eventid) from RequestEvent re where re.share2uid=");
		query.append(currentUser.getId());
		query.append(" and re.begintime<"+startdate.getTimeInMillis()+" and ");
		query.append(" re.endtime>="+startdate.getTimeInMillis()+" and re.endtime<"+enddate.getTimeInMillis()+" ");
		query.append(" and re.iswholeday=0 ");
		return (Long)this.clipEventDao.getUniquerResult(query.toString());
	}
	
	public List getShareEventsByDay(int year, int month, int date,
			int contacttype, User currentUser,Long lastquerycreatetime, int lastcurrentpage) {
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		
		return getShareEventsByPassage(firstDate,secondDate,contacttype,currentUser,lastquerycreatetime,lastcurrentpage);
	}

	public List getviewShareEventsByDay(Calendar now,int contacttype, User currentUser) {
		StringBuffer query=new StringBuffer("from ShareEvent s where ");
		query.append(" s.begintime>"+now.getTimeInMillis());
		
		if(contacttype==1){
			query.append(" and (s.share2uid="+currentUser.getId()+" or exists(SELECT c.id FROM Contact c where c.contactuid=");
			query.append(currentUser.getId());
			query.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0 and c.contacttypeid<>2))");
		}else{
			query.append(" and s.reliedclip=0");
			query.append(" and s.share2uid=0");
		}
		query.append(" order by s.begintime");
		List list=null;
		list=this.clipEventDao.pagingByQuery(query.toString(),0,EventService.SHAREEVENTLOADLENGTH);
		return list;
	}
	
	/**
	 * @param year
	 * @param month
	 * @param date
	 * @param contacttype 0 分享广场 1好友分享
	 * @param currentUser
	 * @param lastquerycreatetime
	 * @return	list[eventid,eventid])
	public List getShareAcceptEventsByDay(int year, int month, int date,
			int contacttype, User currentUser,Long lastquerycreatetime) {
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		
		return getShareAcceptEventsByPassage(firstDate,secondDate,contacttype,currentUser,lastquerycreatetime);
	}
	 */
	
	private List getShareEventsByPassage(Calendar firstDate,
			Calendar secondDate,int contacttype, User currentUser,Long lastquerycreatetime, int lastcurrentpage) {
		StringBuffer query=new StringBuffer("from ShareEvent s where ");
		query.append(" ((s.begintime<="+firstDate.getTimeInMillis()+" and s.endtime>="+firstDate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+firstDate.getTimeInMillis()+" and s.begintime<"+secondDate.getTimeInMillis()+"))");
		
		if(lastquerycreatetime>0l){
			query.append(" and s.createtime<=");
			query.append(lastquerycreatetime);
		}
		
		if(contacttype==1){
			query.append(" and (s.share2uid="+currentUser.getId()+" or exists(SELECT c.id FROM Contact c where c.contactuid=");
			query.append(currentUser.getId());
			query.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0))");
		}else
			query.append(" and s.share2uid=0");
		query.append(" order by s.createtime desc");
		List list=null;
			list=this.clipEventDao.pagingByQuery(query.toString(),lastcurrentpage+1,EventService.SHAREEVENTLOADLENGTH);
		return list;
	}
	/**
	private List getShareAcceptEventsByPassage(Calendar firstDate,Calendar secondDate,
			int contacttype, User currentUser,Long lastquerycreatetime){
		StringBuffer query=new StringBuffer();
		query.append(" select acc.eventid from ShareAcceptmapping acc where acc.uid=");
		query.append(currentUser.getId());
		query.append(" and exists(");
		query.append(" from ShareEvent s where s.eventid=acc.eventid ");
		query.append(" and ((s.begintime<="+firstDate.getTimeInMillis()+" and s.endtime>="+firstDate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+firstDate.getTimeInMillis()+" and s.begintime<"+secondDate.getTimeInMillis()+"))");
		
		if(lastquerycreatetime>0l){
			query.append(" and s.createtime<");
			query.append(lastquerycreatetime);
		}
		
		if(contacttype==1){
			query.append(" and (s.share2uid="+currentUser.getId()+" or exists(SELECT c.id FROM Contact c where c.contactuid=");
			query.append(currentUser.getId());
			query.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0))");
		}else
			query.append(" and s.share2uid=0");
		query.append(" )");
		List list=this.clipEventDao.findByQuery(query.toString());
		return list;
	}
	*/
	/**
	 * @param eventid
	 * @param currentUser
	 * @return
	 * @throws ClipEventNotExistException
	 * 
	 * 如果reliedclip>0 uid可能是当前用户 但reliedclip 的uid不可能是当前用户
	 * 感兴趣的档期，如果是eventtype=2时，生成两条ShareAcceptmapping记录
	 * 
	 * 先判断shareid是否存在，不存在，则说明是感兴趣档期
	 * 如果存在，判断eventtype类型
	 * eventtype==2
	 * 		
	 */
	public ClipEvent interestShareEvent(int eventid, User currentUser) throws ClipEventNotExistException{
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent!=null&&clipEvent.getStatus()==1){
//			//如果是自己的档期，直接返回
			if(clipEvent.getShareid().length()==0){
				if(clipEvent.getUid()==currentUser.getId())
					return clipEvent;
				else
					throw new ClipEventNotExistException("");
			}
			
			if(clipEvent.getUid()==currentUser.getId())
				return clipEvent;
			
			Calendar now=Calendar.getInstance();
			String tempQuery=null;
			List list=null;
			ClipEvent savedClip=null;
			boolean isneedcheckccmap=false;
			int dealeventid=0;
			if(clipEvent.getEventtype()==2){
				//判断感兴趣的档期类型
				if(clipEvent.getSeid()==0){
					//表示为感兴趣ROOT商家档期
					dealeventid=clipEvent.getId();
					tempQuery="from ShareAcceptmapping map where map.accepttype="+ShareAcceptmapping.INTERESTTYPE+" and map.eventid="+dealeventid+" and map.uid="+currentUser.getId();
					list=this.shareacceptmappingDAO.findByQuery(tempQuery);
					if(list==null||list.size()<=0){
						savedClip=cloneClipEvent(clipEvent,currentUser,now,false,false);
						ShareAcceptmapping acceptmapping2=new ShareAcceptmapping();
						acceptmapping2.setAccepttype(ShareAcceptmapping.INTERESTTYPE);
						acceptmapping2.setEventid(dealeventid);
						acceptmapping2.setUid(currentUser.getId());
						acceptmapping2.setFolloweventid(savedClip.getId());
						acceptmapping2.setOpttime(now.getTimeInMillis());
						this.shareacceptmappingDAO.save(acceptmapping2);
						addClipmessageEventMsg(clipEvent.getId(),currentUser.getId(),now,Clipmessage.INTERESTEVENTTYPE,0,false);
						return savedClip;
					}else{
						ShareAcceptmapping map=(ShareAcceptmapping) list.get(0);
						savedClip=this.getDetailClipEvent(map.getFolloweventid());
						return savedClip;
					}
				}else{
					//判断是否已经 WEAK 感兴趣商家档期
//					tempQuery="from ShareAcceptmapping map where map.accepttype=3 and map.eventid="+clipEvent.getSeid()+" and map.uid="+currentUser.getId();
//					list=this.shareacceptmappingDAO.findByQuery(tempQuery);
//					if(list==null||list.size()<=0){
						isneedcheckccmap=true;
//					}
				}
			}
			if(clipEvent.getReliedclip()==0){
				dealeventid=clipEvent.getId();
			}else{
				dealeventid=clipEvent.getReliedclip();
			}
			tempQuery="from ShareAcceptmapping map where map.accepttype=1 and map.eventid="+dealeventid+" and map.uid="+currentUser.getId();
			list=this.shareacceptmappingDAO.findByQuery(tempQuery);
			if(list!=null&&list.size()==1){
				//查到已经感兴趣，修正数据
					//1. 查询是否存在感兴趣的档期
					//2. 不存在则，修正数据，存在则返回档期对象
				ShareAcceptmapping acceptmapping=(ShareAcceptmapping) list.get(0);
				int followeventid=acceptmapping.getFolloweventid();
				tempQuery="from ClipEvent ce where where ce.cliptype=3 and ce.status=1 and ce.id="+followeventid+"  and ce.uid="+currentUser.getId();
				list=this.clipEventDao.findByQuery(tempQuery);
				if(list!=null&&list.size()==1){
					ClipEvent reCE=(ClipEvent) list.get(0);
					if(isneedcheckccmap){
						tempQuery="from ShareAcceptmapping map where map.accepttype=3 and map.eventid="+clipEvent.getSeid()
							+" and map.uid="+currentUser.getId()
							+" and map.followeventid="+reCE.getId();
						list=this.shareacceptmappingDAO.findByQuery(tempQuery);
						if(list==null||list.size()<=0){
							ShareAcceptmapping acceptmapping2=new ShareAcceptmapping();
							acceptmapping2.setAccepttype(ShareAcceptmapping.WEAKINTERESTYYPE);
							acceptmapping2.setEventid(clipEvent.getSeid());
							acceptmapping2.setUid(currentUser.getId());
							acceptmapping2.setFolloweventid(reCE.getId());
							acceptmapping2.setOpttime(now.getTimeInMillis());
							this.shareacceptmappingDAO.save(acceptmapping2);
						}
					}
					return reCE;
				}else{
					tempQuery="delete from ShareAcceptmapping map where map.accepttype=1 and map.eventid="+dealeventid+" and map.uid="+currentUser.getId();
					this.shareacceptmappingDAO.excuteUpdateQuery(tempQuery);
				}
			}
				//说明还没感兴趣
			savedClip=cloneClipEvent(clipEvent,currentUser,now,false,false);
			ShareAcceptmapping acceptmapping2=new ShareAcceptmapping();
			acceptmapping2.setAccepttype(ShareAcceptmapping.INTERESTTYPE);
			acceptmapping2.setEventid(dealeventid);
			acceptmapping2.setUid(currentUser.getId());
			acceptmapping2.setFolloweventid(savedClip.getId());
			acceptmapping2.setOpttime(now.getTimeInMillis());
			this.shareacceptmappingDAO.save(acceptmapping2);
			if(isneedcheckccmap){
				acceptmapping2=new ShareAcceptmapping();
				acceptmapping2.setAccepttype(ShareAcceptmapping.WEAKINTERESTYYPE);
				acceptmapping2.setEventid(clipEvent.getSeid());
				acceptmapping2.setUid(currentUser.getId());
				acceptmapping2.setFolloweventid(savedClip.getId());
				acceptmapping2.setOpttime(now.getTimeInMillis());
				this.shareacceptmappingDAO.save(acceptmapping2);
			}
			int reliedclip=clipEvent.getReliedclip();
			int addmsgeventid=0;
			if(clipEvent.getReliedclip()==0){
				addmsgeventid=clipEvent.getId();
			}else{
				addmsgeventid=clipEvent.getReliedclip();
			}
			addClipmessageEventMsg(addmsgeventid,currentUser.getId(),now,Clipmessage.INTERESTEVENTTYPE,reliedclip,true);
			
			return savedClip;
		}else{
			throw new ClipEventNotExistException("");
		}
	}

	/**
	 * 添加评论，及事件通知Msgnotice
	 * 
	 * @param eventid
	 * @param uid
	 * @param now
	 * @param msgtype
	 * @param reliedclip
	 * @param isnotice
	 */
	public void addClipmessageEventMsg(int eventid,int uid,Calendar now,int msgtype,int reliedclip,boolean isnotice){
		Clipmessage clipmessage=new Clipmessage();
		clipmessage.setContent("");
		clipmessage.setEventid(eventid);
		clipmessage.setReplytime(now.getTimeInMillis());
		clipmessage.setUid(uid);
		clipmessage.setMsgtype(msgtype);
		this.clipmessageDAO.save(clipmessage);
		if(isnotice){
			String sharemappingSQL="from Sharemapping map where map.eventid="+eventid+" and map.acceptstatus=1";
			List list=this.sharemappingDAO.findByQuery(sharemappingSQL);
			if(list!=null&&list.size()>0){
				for (Object object : list) {
					Sharemapping sharemapping=(Sharemapping) object;
					int share2uid=sharemapping.getShare2uid();
					if(uid!=share2uid){
						MsgNotice msgNotice=new MsgNotice();
						msgNotice.setEventid(eventid);
						msgNotice.setCheckstatus(0);
						msgNotice.setMsgid(clipmessage.getId());
						msgNotice.setUid(share2uid);
						msgNotice.setMsgtime(now.getTimeInMillis());
						this.msgNoticeDAO.save(msgNotice);
					}
				}
			}
			if(reliedclip>0){//表示需要通知档期发起呼朋唤友的人
				ClipEvent clipEvent=this.getDetailClipEvent(reliedclip);
				if(clipEvent.getUid()!=uid){
					MsgNotice msgNotice=new MsgNotice();
					msgNotice.setEventid(eventid);
					msgNotice.setCheckstatus(0);
					msgNotice.setMsgid(clipmessage.getId());
					msgNotice.setUid(clipEvent.getUid());
					msgNotice.setMsgtime(now.getTimeInMillis());
					this.msgNoticeDAO.save(msgNotice);
				}
			}
		}
	}
	
	/**
	 * @param eventid
	 * @param uid
	 * @param msgtype 只允许 CANCELINTERESTEVENTTYPE=2;CANCELFAVOREVENTTYPE=7;
	 * @param reliedclip
	 * @param isnotice
	 */
	public void removeClipmessageEventMsg(int eventid,int uid,int msgtype,boolean isnotice){
		String clipmessageSQL="from Clipmessage msg where msg.eventid=? and msg.uid=? and msg.msgtype=?";
		List list=this.clipmessageDAO.findByQuery(clipmessageSQL,new Object[]{eventid,uid,msgtype});
		if(list!=null&&list.size()>0){
			for (Object object : list) {
				Clipmessage msg=(Clipmessage) object;
				if(isnotice){
					String msgNoticeSQL="delete from MsgNotice notice where notice.msgid="+msg.getId();
					this.msgNoticeDAO.excuteUpdateQuery(msgNoticeSQL);
				}
				this.clipmessageDAO.delete(msg);
			}
		}
	}
	
	
	private void cloneClipAddressref(int rooteventid, int clonedeventid) {
		List list=this.addressrefDAO.findByQuery("from ClipAddressref ref where ref.eventid=?", new Object[]{rooteventid});
		if(list!=null&&list.size()>0){
			ClipAddressref ref=(ClipAddressref) list.get(0);
			ClipAddressref newref=new ClipAddressref();
			newref.setEventid(clonedeventid);
			newref.setLatitude(ref.getLatitude());
			newref.setLongitude(ref.getLongitude());
			this.addressrefDAO.save(newref);
		}
	}

	private void cloneClipeventPic(int rooteventid, int clonedeventid) {
		List list=this.clipeventPicDAO.findByQuery("from ClipeventPic pic where pic.eventid=?", new Object[]{rooteventid});
		if(list!=null&&list.size()>0){
			ClipeventPic pic=(ClipeventPic) list.get(0);
			ClipeventPic newpic=new ClipeventPic();
			newpic.setEventid(clonedeventid);
			newpic.setPicurl(pic.getPicurl());
			this.clipeventPicDAO.save(newpic);
		}
		
	}

	public ClipEvent saveShareEvent(int eventid, User currentUser) throws ClipEventNotExistException{
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		if(clipEvent!=null&&clipEvent.getStatus()==1){
			int reliedclip=clipEvent.getReliedclip();
			String tempQuery=null;
			if(reliedclip>0)
				tempQuery="from ClipEvent ce where ce.cliptype=3 and ce.status=1 and ce.uid="+currentUser.getId()+" and ce.reliedclip="+reliedclip+" and ce.fuid="+clipEvent.getUid();
			else
				tempQuery="from ClipEvent ce where ce.cliptype=3 and ce.status=1 and ce.uid="+currentUser.getId()+" and ce.reliedclip="+clipEvent.getId();
			List list=this.clipEventDao.findByQuery(tempQuery);
			if(list!=null&&list.size()>0){
				ClipEvent savedClip=(ClipEvent) list.get(0);
				String shareid=savedClip.getShareid();
				if(shareid==null||shareid.length()<=0){
					shareid=ToolsUtils.getUUID();
					savedClip.setShareid(shareid);
					this.clipEventDao.attachDirty(savedClip);
				}
					
				//说明已经存在保存档期
				return savedClip;
			}
			ClipEvent currentUserEvent=(ClipEvent) clipEvent.clone();
			currentUserEvent.setEventtype(currentUser.getUsertype());
			currentUserEvent.setId(0);
			currentUserEvent.setUid(currentUser.getId());
//			if(reliedclip>0)
//				currentUserEvent.setFuid(clipEvent.getUid());
//			else
//				currentUserEvent.setFuid(0);
			currentUserEvent.setCliptype(3);
			Calendar now=Calendar.getInstance();
			currentUserEvent.setCreatetime(now.getTimeInMillis());
			currentUserEvent.setShareid(ToolsUtils.getUUID());
			if(currentUserEvent.getReliedclip()==0){
				currentUserEvent.setReliedclip(clipEvent.getId());
			}
			this.clipEventDao.save(currentUserEvent);
			
			if(reliedclip>0){
				ClipEvent orientClip=this.clipEventDao.findById(clipEvent.getReliedclip());
				if(orientClip!=null&&orientClip.getStatus()==1){
					this.shareacceptmappingDAO.saveIfNotExist(reliedclip, currentUserEvent.getId(), currentUser.getId(),1);
					ShareAcceptmapping acceptmapping2=new ShareAcceptmapping();
					acceptmapping2.setAccepttype(1);
					acceptmapping2.setEventid(orientClip.getId());
					acceptmapping2.setUid(currentUser.getId());
					acceptmapping2.setFolloweventid(currentUserEvent.getId());
					this.shareacceptmappingDAO.save(acceptmapping2);
				}else{
					throw new ClipEventNotExistException("");
				}
			}else{
				ShareAcceptmapping acceptmapping=new ShareAcceptmapping();
				acceptmapping.setAccepttype(1);
				acceptmapping.setEventid(clipEvent.getId());
				acceptmapping.setUid(currentUser.getId());
				acceptmapping.setFolloweventid(currentUserEvent.getId());
				this.shareacceptmappingDAO.save(acceptmapping);
			}
			
			
			
			return currentUserEvent;
		}else{
			throw new ClipEventNotExistException("");
		}
	}
	/**
	 * @param eventid
	 * @param currentUser
	 * @param sharelist
	 * @return
	 */
//	public String forwardShareEvent(int eventid, User currentUser,String sharelist) throws ClipEventNotExistException{
//		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
//		if(clipEvent!=null&&clipEvent.getStatus()==1){
//			int reliedclip=clipEvent.getReliedclip();
//			ClipEvent rootEvent=reliedclip>0?this.clipEventDao.findById(reliedclip):clipEvent;
//			if(rootEvent==null||rootEvent.getStatus()!=1){
//				throw new ClipEventNotExistException("");
//			}
//			ClipEvent userSavedClip=null;
//			Calendar now=Calendar.getInstance();
//			if(rootEvent.getUid()==currentUser.getId()){
//				//说明是自己发起的
//				userSavedClip=rootEvent;
//			}else{
//				int savedeventid=0;
//				List templist=this.sharemappingDAO.findByQuery("from ShareAcceptmapping acc where acc.eventid="+rootEvent.getId()+" and acc.accepttype<>4 and acc.uid="+currentUser.getId());
//				if(templist!=null&&templist.size()>0){//说明已经 感兴趣 或 转发 过 源档期
//					ShareAcceptmapping shareAcceptmapping=(ShareAcceptmapping) templist.get(0);
//					if(shareAcceptmapping.getAccepttype()==ShareAcceptmapping.INTERESTTYPE){
//						shareAcceptmapping.setAccepttype(ShareAcceptmapping.ALLTYPE);
//						this.shareacceptmappingDAO.attachDirty(shareAcceptmapping);
//					}
//					savedeventid=shareAcceptmapping.getFolloweventid();
//					userSavedClip=this.clipEventDao.findById(savedeventid);
//				}else{//说明 没有 感兴趣 或 转发 过 源档期
//					userSavedClip=cloneClipEvent(clipEvent,currentUser,now);
//					ShareAcceptmapping shareAcceptmapping=new ShareAcceptmapping();
//				}
//			}
//			
//			userSavedClip.setCreatetime(now.getTimeInMillis());
//			if(userSavedClip.getShareid().length()==0){
//				userSavedClip.setShareid(ToolsUtils.getUUID());
//			}
//			this.clipEventDao.attachDirty(userSavedClip);
//			
//			// start 保存 分享 对象 映射
//			List sharemaps=this.sharemappingDAO.findByEventid(userSavedClip.getId());
//			boolean isallshare=false;
//			for (Object object : sharemaps) {
//				Sharemapping sharemapping=(Sharemapping) object;
//				if(sharemapping.getShare2uid()==0){
//					isallshare=true;
//					break;
//				}
//			}
//			if(!isallshare){
//				List list=new ArrayList();//share2uid
//				boolean islist=true;
//				if(sharelist.indexOf(",")>0){
//					String[] groupids=sharelist.split(",");
//					for (String sgroupid : groupids) {
//						int groupid=Integer .parseInt(sgroupid);
//						List templist=getContactIdsByGroupId(groupid);
//						addContactList2List(templist,list);
//					}
//					
//				}else{
//					int groupid=Integer.parseInt(sharelist);
//					if(groupid==0){
//						this.sharemappingDAO.excuteUpdateQuery("delete from Sharemapping map where map.eventid="+userSavedClip.getId());
//						Sharemapping sharemapping=new Sharemapping();
//						sharemapping.setEventid(userSavedClip.getId());
//						sharemapping.setShare2uid(0);
//						this.sharemappingDAO.save(sharemapping);
//						islist=false;
//					}else
//						list=getContactIdsByGroupId(groupid);
//					
//				}
//				
//				if(islist){
//					List uidlist=new ArrayList();
//					for (Object object : sharemaps) {
//						Sharemapping sharemapping=(Sharemapping) object;
//						int savedShare2uid=sharemapping.getShare2uid();
//						if(list.contains(savedShare2uid)){
//							list.remove(savedShare2uid);
//						}
//					}
//					for (Object object : list) {
//						int share2uid=(Integer)object;
//						Sharemapping sharemapping=new Sharemapping();
//						sharemapping.setEventid(userSavedClip.getId());
//						sharemapping.setShare2uid(share2uid);
//						this.sharemappingDAO.save(sharemapping);
//					}
//				}
//			}
//			
//			//end
//			
//			// start判断是否存在 <reliedclip> 的数据，增加统计
//			if(reliedclip>0){
//				ClipEvent orientClip=this.clipEventDao.findById(clipEvent.getReliedclip());
//				if(orientClip!=null&&orientClip.getStatus()==1){
//					this.shareacceptmappingDAO.saveIfNotExist(reliedclip,userSavedClip.getId(),currentUser.getId(),ShareAcceptmapping.FORWARDTYPE);
//					
//					this.shareacceptmappingDAO.saveIfNotExist(clipEvent.getId(),userSavedClip.getId(),currentUser.getId(),ShareAcceptmapping.FORWARDTYPE);
//				}else{
//					throw new ClipEventNotExistException("");
//				}
//			}else{
//				this.shareacceptmappingDAO.saveIfNotExist(clipEvent.getId(),userSavedClip.getId(),currentUser.getId(),ShareAcceptmapping.FORWARDTYPE);
//			}
//			// end
//			return userSavedClip.getShareid();
//		}else{
//			throw new ClipEventNotExistException("");
//		}
//	}
	
	public ClipEvent cloneClipEvent(ClipEvent orientClip,User currentUser, Calendar now,boolean isGenerateshareid,boolean isforward){
		ClipEvent clonedEvent=(ClipEvent) orientClip.clone();
		clonedEvent.setId(0);
		clonedEvent.setUid(currentUser.getId());
		clonedEvent.setCliptype(3);
		clonedEvent.setCreatetime(now.getTimeInMillis());
		if(isGenerateshareid)
			clonedEvent.setShareid(ToolsUtils.getUUID());
		else
			clonedEvent.setShareid("");
		if(isforward){
			clonedEvent.setReliedclip(0);
		}else{
			clonedEvent.setReliedclip(orientClip.getId());
		}
		if(orientClip.getSeid()==0){//说明是源头
			clonedEvent.setSeid(orientClip.getId());
		}
		this.clipEventDao.save(clonedEvent);
		cloneClipeventPic(orientClip.getId(),clonedEvent.getId());
		cloneClipAddressref(orientClip.getId(),clonedEvent.getId());
		return clonedEvent;
	}
	
	/**
	 * @param eventid
	 * @param currentUser
	 * @param sharelist
	 * @param share2userlist
	 * @return
	 * @throws ClipEventNotExistException
	 */
	public String forwardShareEvent(int eventid, User currentUser,String share2userlist,String mlist,long invitetime) throws ClipEventNotExistException{
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent!=null&&clipEvent.getStatus()==1){
			//查看转发的档期是否存在，eventtype==2是商家档期，要查看商家档期是否存在
			ClipEvent userSavedClip=null;
			if(clipEvent.getCliptype()==3){
				ClipEvent rootEvent=null;
				if(clipEvent.getEventtype()==1){
					if(clipEvent.getReliedclip()>0){
						rootEvent=this.clipEventDao.findById(clipEvent.getReliedclip());
					}else
						rootEvent=clipEvent;
				}else if(clipEvent.getEventtype()==2){
					rootEvent=clipEvent.getSeid()==0?clipEvent:this.clipEventDao.findById(clipEvent.getSeid());
				}
				if(rootEvent==null||rootEvent.getStatus()!=1){
					throw new ClipEventNotExistException("");
				}else if(rootEvent.getUid()==currentUser.getId()){
					return null;
				}
				Calendar now=Calendar.getInstance();
				if(rootEvent.getUid()==currentUser.getId()){
					//不存在这样的情况
					userSavedClip=rootEvent;
				}else{
					userSavedClip=cloneClipEvent(clipEvent,currentUser,now,true,true);
					if(clipEvent.getEventtype()==2&&invitetime>0l)
						userSavedClip.setInvitetime(invitetime);
					this.clipEventDao.attachDirty(userSavedClip);
					ShareAcceptmapping shareAcceptmapping=new ShareAcceptmapping();
					shareAcceptmapping.setAccepttype(ShareAcceptmapping.FORWARDTYPE);
					shareAcceptmapping.setEventid(rootEvent.getId());
					shareAcceptmapping.setUid(currentUser.getId());
					shareAcceptmapping.setFolloweventid(userSavedClip.getId());
					shareAcceptmapping.setOpttime(now.getTimeInMillis());
					this.shareacceptmappingDAO.save(shareAcceptmapping);
					
				}
				
				addClipmessageEventMsg(clipEvent.getId(), currentUser.getId(), now, Clipmessage.FORWARDEVENTTYPE, 0, true);
			}else if(clipEvent.getCliptype()==1){
				if(clipEvent.getUid()!=currentUser.getId()){
					return null;
				}else{
					clipEvent.setCliptype(3);
					clipEvent.setShareid(ToolsUtils.getUUID());
					this.clipEventDao.attachDirty(clipEvent);
					userSavedClip=clipEvent;
				}
			}
			
			List list=new ArrayList();//share2uid
			if(share2userlist!=null&&share2userlist.length()>0){
				if(share2userlist.indexOf(",")>0){
					String[] uids=share2userlist.split(",");
					for (String suid : uids) {
						int uid=Integer.parseInt(suid);
						list.add(uid);
					}
				}else{
					list.add(Integer.parseInt(share2userlist));
				}
			}
			for (Object object : list) {
				int share2uid=(Integer)object;
				Sharemapping sharemapping=new Sharemapping();
				sharemapping.setEventid(userSavedClip.getId());
				sharemapping.setShare2uid(share2uid);
				int flag=this.isMobileNoticeUser(mlist, share2uid)?1:0;
				sharemapping.setMobilenotice(flag);
				this.sharemappingDAO.save(sharemapping);
				SystemMessage message=new SystemMessage();
				message.setEventid(clipEvent.getId());
				message.setFromuid(clipEvent.getUid());
				message.setMsgtime(Calendar.getInstance().getTimeInMillis());
				message.setMsgtype(SystemMessage.ADDTYPE);
				message.setUid(share2uid);
				message.setCheckstatus(0);
				this.systemMessageDAO.save(message);
				
				sendInvitedEmail(currentUser.getName(),share2uid,userSavedClip,flag);
				
			}
			
			//end
			
			return userSavedClip.getShareid();
		}else{
			throw new ClipEventNotExistException("");
		}
	}
	
	public void forwardMoreWithShareEvent(int eventid, User currentUser,String share2userlist,String mlist) throws ClipEventNotExistException{
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent!=null&&clipEvent.getStatus()==1&&clipEvent.getUid()==currentUser.getId()){
			//查看转发的档期是否存在，eventtype==2是商家档期，要查看商家档期是否存在
			if(clipEvent.getCliptype()==3){
				ClipEvent rootEvent=null;
				if(clipEvent.getEventtype()==2){
					rootEvent=clipEvent.getSeid()==0?clipEvent:this.clipEventDao.findById(clipEvent.getSeid());
					if(rootEvent==null||rootEvent.getStatus()!=1){
						throw new ClipEventNotExistException("");
					}else if(rootEvent.getUid()==currentUser.getId()){
						return;
					}
				}
//				Calendar now=Calendar.getInstance();
//				if(rootEvent.getUid()==currentUser.getId()){
//					//不存在这样的情况
//				}
				
			
				List list=new ArrayList();//share2uid
				if(share2userlist!=null&&share2userlist.length()>0){
					if(share2userlist.indexOf(",")>0){
						String[] uids=share2userlist.split(",");
						for (String suid : uids) {
							int uid=Integer.parseInt(suid);
							list.add(uid);
						}
					}else{
						list.add(Integer.parseInt(share2userlist));
					}
				}
				for (Object object : list) {
					int share2uid=(Integer)object;
					Sharemapping sharemapping=new Sharemapping();
					sharemapping.setEventid(clipEvent.getId());
					sharemapping.setShare2uid(share2uid);
					int flag=this.isMobileNoticeUser(mlist, share2uid)?1:0;
					sharemapping.setMobilenotice(flag);
					this.sharemappingDAO.save(sharemapping);
					SystemMessage message=new SystemMessage();
					message.setEventid(clipEvent.getId());
					message.setFromuid(clipEvent.getUid());
					message.setMsgtime(Calendar.getInstance().getTimeInMillis());
					message.setMsgtype(SystemMessage.ADDTYPE);
					message.setUid(share2uid);
					message.setCheckstatus(0);
					this.systemMessageDAO.save(message);
					
					sendInvitedEmail(currentUser.getName(),share2uid,clipEvent,flag);
					
				}
			}
			
			//end
			return;
		}else{
			throw new ClipEventNotExistException("");
		}
	}

	public Long countLastShareEventsByDay(int year, int month, int date,
			int contacttype, User currentUser, Long getLastCreatetime) {
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		
		StringBuffer query=new StringBuffer("select count(*) from shareevent s where ");
		query.append(" ((s.begintime<="+firstDate.getTimeInMillis()+" and s.endtime>="+firstDate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+firstDate.getTimeInMillis()+" and s.begintime<"+secondDate.getTimeInMillis()+"))");
		query.append(" and s.createtime>");
		query.append(getLastCreatetime);
		if(contacttype==1){
			query.append(" and (s.share2uid="+currentUser.getId()+" or exists(SELECT c.id FROM Contact c where c.contactuid=");
			query.append(currentUser.getId());
			query.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0))");
		}else
			query.append(" and s.share2uid=0");
		
		List list=this.clipEventDao.findBySqlQuery(query.toString());
		if(list!=null&&list.size()>0){
			BigInteger count=(BigInteger ) list.get(0);
			return count.longValue();
		}else
			return 0l;
	}

	public Long countShareEventsByDayAndUser(Calendar startdate, User visitUser) {
		Calendar enddate=(Calendar) startdate.clone();
		enddate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer("select count(*) from shareevent s where ");
		query.append(" ((s.begintime<="+startdate.getTimeInMillis()+" and s.endtime>="+startdate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+startdate.getTimeInMillis()+" and s.begintime<"+enddate.getTimeInMillis()+"))");
		query.append(" and s.uid=");
		query.append(visitUser.getId());
		List list=this.clipEventDao.findBySqlQuery(query.toString());
		if(list!=null&&list.size()>0){
			BigInteger count=(BigInteger ) list.get(0);
			return count.longValue();
		}else
			return 0l;
	}

	public List getUsersShareEventsByDay(int year, int month, int date,
			String visituid,User currentUser, Long lastquerycreattime,int lastcurrentpage) {
		int vuid=Integer.parseInt(visituid);
		User visitUser=vuid==0?currentUser:this.userDAO.findById(vuid);
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer("from ClipEvent ce where ");
		query.append(" (((ce.begintime<="+firstDate.getTimeInMillis()+" and ce.endtime>="+firstDate.getTimeInMillis()+") or ");
		query.append("  (ce.begintime>"+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis()+"))");
		query.append("  or ( ");
		query.append(" ce.invitetime>0 and ce.invitetime>="+firstDate.getTimeInMillis()+" and ce.invitetime<"+secondDate.getTimeInMillis());
		query.append(" ) ) ");;
		query.append(" and ce.reliedclip=0 and ce.status=1 and ce.uid=");
		query.append(visitUser.getId());
		if(visitUser.getUsertype()==2){
			query.append(" and ce.cliptype=3 ");
		}else{
			if(currentUser.getId()==vuid||vuid==0)
				query.append(" and ( ce.cliptype=4 or ce.cliptype=3)");
			else
				query.append(" and ( ce.cliptype=4 or ( ce.cliptype=3 and exists (select map.id from Sharemapping map where map.eventid=ce.id and map.share2uid="+currentUser.getId()+") ) )");
		}
		if(lastquerycreattime>0l){
			query.append(" and ce.createtime<=");
			query.append(lastquerycreattime);
		}
		query.append(" order by ce.createtime desc");
		List list=null;
			list=this.clipEventDao.pagingByQuery(query.toString(),lastcurrentpage+1,EventService.SHAREEVENTLOADLENGTH);
		return list;
	}

	public List getUsersShareAcceptEventsByDay(int year, int month, int date,
			String visituid, User currentUser, Long lastquerycreatetime) {
		if(Integer.parseInt(visituid)==0||Integer.parseInt(visituid)==currentUser.getId())
			return null;
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer();
		query.append(" select acc.eventid from ShareAcceptmapping acc where acc.uid=");
		query.append(currentUser.getId());
		query.append(" and exists(");
		query.append(" from ShareEvent s where s.eventid=acc.eventid ");
		query.append(" and ((s.begintime<="+firstDate.getTimeInMillis()+" and s.endtime>="+firstDate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+firstDate.getTimeInMillis()+" and s.begintime<"+secondDate.getTimeInMillis()+"))");
		query.append(" and s.uid=");
		query.append(visituid);
		if(lastquerycreatetime>0l){
			query.append(" and s.createtime<");
			query.append(lastquerycreatetime);
		}
		
		query.append(" )");
		List list=this.clipEventDao.findByQuery(query.toString());
		return list;
	}

	public int getUsersRelationShip(int currentuid,int visituid){
		List list=this.contactDAO.findByQuery("from Contact c where c.status=1 and c.uid="+visituid+" and c.contactuid="+currentuid);
		if(list!=null&&list.size()>0){
			Contact contact=(Contact) list.get(0);
			return contact.getContacttypeid();
		}else{
			return 0;
		}
	}
	
	/**
	 * cliptype==3
	 * @param clipevent
	 * @return List index: 	0	感兴趣	】
	 * 						1	转发		】	eventtype==2时，显示
	 * 						2	喜欢		】
	 * 						3	评论
	 */
	public List getStatAboutClipEvent(ClipEvent clipevent,User currentUser) {
		List list=new ArrayList();
		int parentid=clipevent.getReliedclip();
		String sql=null;
		int counteventid=0;
		if(parentid>0){
			counteventid=parentid;
		}else{
			counteventid=clipevent.getId();
		}
		if(clipevent.getCliptype()==3){
			//eventtype==2 seid==0 eventuid==currentuseruid
			if(currentUser.getUsertype()==2){
				//商家查看自己发起的档期
			}else{
				if(clipevent.getEventtype()==2&&(clipevent.getSeid()==0||clipevent.getSeid().equals(clipevent.getReliedclip()))){
					//直接看商家/查看自己直接感兴趣的商家档期
					if(clipevent.getSeid()==0)
						sql="select count(distinct map.uid) from ShareAcceptmapping map where map.accepttype=1  and map.eventid="+clipevent.getId();
					else
						sql="select count(distinct map.uid) from ShareAcceptmapping map where map.accepttype=1  and map.eventid="+clipevent.getSeid();	
					Long interestcount=(Long) this.shareacceptmappingDAO.countByQuery(sql);
					list.add(interestcount);
					if(clipevent.getSeid()==0)
						sql="select count(distinct map.uid) from ShareAcceptmapping map where map.accepttype=2  and map.eventid="+clipevent.getId();
					else
						sql="select count(distinct map.uid) from ShareAcceptmapping map where map.accepttype=2  and map.eventid="+clipevent.getSeid();	
					Long forwardcount=(Long) this.shareacceptmappingDAO.countByQuery(sql);
					list.add(forwardcount);
					if(clipevent.getSeid()==0)
						sql="select count(distinct map.uid) from ShareFavormapping map where map.eventid="+clipevent.getId();
					else
						sql="select count(distinct map.uid) from ShareFavormapping map where map.eventid="+clipevent.getSeid();	
					Long favorcount=(Long) this.sharefavormappingDAO.countByQuery(sql);
					list.add(favorcount);
				}
			}
			sql="select count(*) from Clipmessage msg where msg.eventid="+counteventid;
			Long msgcount=(Long) this.clipmessageDAO.countByQuery(sql);
			list.add(msgcount);
		}else if(clipevent.getCliptype()==4){
			sql="select count(*) from Clipmessage msg where msg.eventid="+clipevent.getId();
			Long msgcount=(Long) this.clipmessageDAO.countByQuery(sql);
			list.add(msgcount);
		}
		return list;
	}

	public ClipEvent getUserAcceptShareEvent(int eventid, Integer uid) {
		ClipEvent clipEvent=this.clipEventDao.findById(eventid);
		if(clipEvent.getUid()==uid){
			return clipEvent;
		}else{
			ClipEvent rootEvent=clipEvent.getReliedclip()>0?this.clipEventDao.findById(clipEvent.getReliedclip()):clipEvent;
			if(rootEvent.getUid()==uid)
				return rootEvent;
			StringBuffer query=new StringBuffer();
			query.append(" from ShareAcceptmapping acc where acc.uid=");
			query.append(uid);
			query.append(" and acc.eventid=");
			query.append(rootEvent.getId());
			List list=this.clipEventDao.findByQuery(query.toString());
			if(list!=null&&list.size()>0){
				int felloweventid=((ShareAcceptmapping)list.get(0)).getFolloweventid();
				return this.clipEventDao.findById(felloweventid);
			}else
				return null;
		}
	}
	
	/**
	 * @param currentuid 
	 * @param otheruid
	 * 		current 与 other的关系
	 * @return 	如果双方是好友，返回备注名
	 * 			如果不是好友，则返回真实名
	 * 			如果是游客，返回真实名
	 */
	public String getUserName(int currentuid,int otheruid){
		if(currentuid==0){
			User user=this.userDAO.findById(otheruid);
			return user.getName();
		}else{
			List list=this.contactDAO.findByQuery("from Contact c where c.status=1 and c.uid="+currentuid+" and c.contactuid="+otheruid);
			if(list!=null&&list.size()>0){
				Contact contact=(Contact) list.get(0);
				return contact.getName();
			}else{
				User user=this.userDAO.findById(otheruid);
				return user.getName();
			}
		}
	}

	public boolean checkIsInvitedEvent(Integer eventid) {
		List list=this.alertUserDAO.findByEventid(eventid);
		if(list!=null&&list.size()>0)
			return true;
		else
			return false;
	}

	public Long countShareEventsByDayAndUser(Calendar startdate,
			User visitUser,int currentuid) {
		Calendar enddate=(Calendar) startdate.clone();
		enddate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer("select count(ce.id) from ClipEvent ce where ");
		query.append(" (((ce.begintime<="+startdate.getTimeInMillis()+" and ce.endtime>="+startdate.getTimeInMillis()+") or ");
		query.append("  (ce.begintime>"+startdate.getTimeInMillis()+" and ce.begintime<"+enddate.getTimeInMillis()+"))");
		query.append("  or (");
		query.append(" ce.invitetime>0 and ce.invitetime>= "+startdate.getTimeInMillis()+" and ce.invitetime<"+enddate.getTimeInMillis());
		query.append(" ) ) ");
		query.append(" and ce.reliedclip=0 and ce.status=1 and ce.uid=");
		query.append(visitUser.getId());
		if(visitUser.getUsertype()==2){
			query.append(" and ce.cliptype=3");
		}else{
			if(visitUser.getId()!=currentuid)
				query.append(" and ( ce.cliptype=4 or ( ce.cliptype=3 and exists (select map.id from Sharemapping map where map.eventid=ce.id and map.share2uid="+currentuid+") ) )");
			else
				query.append(" and ( ce.cliptype=4 or ce.cliptype=3)");
		}
		List list=this.clipEventDao.findByQuery(query.toString());
		if(list!=null&&list.size()>0){
			return (Long) list.get(0);
		}else
			return 0l;
	}

	public Long countEndedShareEventsByDayAndUser(Calendar startdate,
			User visitUser, int currentuid) {
		Calendar enddate=(Calendar) startdate.clone();
		enddate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer("select count(distinct s.eventid) from shareevent s where ");
		query.append("  s.endtime>="+startdate.getTimeInMillis()+" and s.endtime<"+enddate.getTimeInMillis());
		query.append(" and s.iswholeday=0 and s.uid=");
		query.append(visitUser.getId());
		if(visitUser.getId()!=currentuid)
			query.append(" and ( s.share2uid=0 or s.share2uid="+currentuid+" )");
		List list=this.clipEventDao.findBySqlQuery(query.toString());
		if(list!=null&&list.size()>0){
			BigInteger count=(BigInteger ) list.get(0);
			return count.longValue();
		}else
			return 0l;
	}

	/**
	 * @param eventid
	 * @return type name list
	 */
	public List loadShareTargetsByEventid(int eventid){
		List contacttypelist=this.sharemappingDAO.findByEventid(eventid);
		List typelist=this.contactTypeDAO.findAll();
		List typenames=new ArrayList();
		for (Object object : contacttypelist) {
			Sharemapping sharemapping=(Sharemapping) object;
			if(sharemapping.getContacttypeid()==0){
				typenames.add("全部");
			}else{
				
				for (Object object2 : typelist) {
					ContactType contactType=(ContactType) object2;
					if(sharemapping.getContacttypeid().equals(contactType.getId())){
						typenames.add(contactType.getTypename());
						break;
					}
				}
			}
		}
		return typenames;
	}

	public int getUserAcceptShareEventid(ClipEvent event, int uid) {
		if(event.getUid()==uid){
			return event.getId();
		}else{
			
			StringBuffer query=new StringBuffer();
			query.append(" from ShareAcceptmapping acc where acc.accepttype=2 and acc.uid=");
			query.append(uid);
			query.append(" and acc.eventid=");
			query.append(event.getId());
			List list=this.clipEventDao.findByQuery(query.toString());
			if(list!=null&&list.size()>0){
				ShareAcceptmapping acceptmapping=(ShareAcceptmapping) list.get(0);
				return acceptmapping.getFolloweventid();
			}else{
				return 0;
			}
		}
	}

	public List getShareMappingList(int eventid){
		return this.sharemappingDAO.findByQuery("from Sharemapping map where map.eventid="+eventid);
	}

	public List getAllEventsByDay(int year, int month, int date,User currentUser) {
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
//		StringBuffer query=new StringBuffer("from ClipEvent ce where (ce.uid="+currentUser.getId()+" and (ce.cliptype=1 or ce.cliptype=3) and ce.status=1 and ");
//		query.append(" ((ce.begintime<="+firstDate.getTimeInMillis()+" and ce.endtime>="+firstDate.getTimeInMillis()+") or ");
//		query.append("  (ce.begintime>"+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis()+")) )");
//		query.append(" or exists (from ShareEvent s where ");
//		query.append(" ce.id=s.eventid and ((s.begintime<="+firstDate.getTimeInMillis()+" and s.endtime>="+firstDate.getTimeInMillis()+") or ");
//		query.append("  (s.begintime>"+firstDate.getTimeInMillis()+" and s.begintime<"+secondDate.getTimeInMillis()+"))");
//		query.append(" and (s.share2uid="+currentUser.getId()+" or exists(SELECT c.id FROM Contact c where c.contactuid=");
//		query.append(currentUser.getId());
//		query.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0)) )");
//		query.append(" order by ce.createtime desc");
		List list=null;
			list=this.clipEventDao.findByNamedQuery("alleventbyday",new Object[]{currentUser.getId(),firstDate.getTimeInMillis(),secondDate.getTimeInMillis()});
		return list;
	}

	public List getInviteEventsByDay(int year, int month, int date,User currentUser) {
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		String query="from ClipEvent ce where ce.uid="+currentUser.getId()+" and ce.createtime>="+firstDate.getTimeInMillis()+" and ce.createtime<"+secondDate.getTimeInMillis()
			+" and (ce.cliptype=1 or ce.cliptype=3) and ce.reliedclip>0 and ce.status=0 and exists(from AlertUser au where au.eventid=ce.reliedclip)";
		List clips=clipEventDao.findByQuery(query);
		return clips;
	}
	
	public List getMemoEventsByDay(int year, int month, int date,User currentUser) {
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		String query1="from ClipEvent clip where clip.cliptype=2 and clip.status=1 and clip.uid="+currentUser.getId();
		if(firstDate!=null){
			SimpleDateFormat dateFormat=new SimpleDateFormat("MMdd");
			query1+=" and clip.begintime<"+secondDate.getTimeInMillis()
					+" and clip.endtime="+"1"+dateFormat.format(firstDate.getTime());
		}
		return clipEventDao.findByQuery(query1);
	}
	
	public List getAlertEventsTilnow(Calendar now,User currentUser) {
		String query="from ClipEvent ce where ce.status=1 and ce.uid="+currentUser.getId()+" and ce.alerttime<="+now.getTimeInMillis()+" order by ce.alerttime desc";
		return clipEventDao.findByQuery(query);
	}

	public AlertUser getInviteEventAlertUser(Integer reliedclip, int uid) {
		StringBuffer query=new StringBuffer();
		query.append("from AlertUser au where au.eventid=");
		query.append(reliedclip);
		if(uid>0){
			query.append(" and au.contactuid=");
			query.append(uid);
		}
		List list=this.alertUserDAO.findByQuery(query.toString());
		if(list!=null&&list.size()>0){
			return (AlertUser) list.get(0);
		}else
			return null;
	}

	public String cancelShareEvent(String shareid, User currentUser) {
		List list=this.clipEventDao.findByQuery("from ClipEvent ce where ce.shareid='"+shareid+"' and ce.uid="+currentUser.getId());
		ClipEvent ce=(ClipEvent) list.get(0);
		return this.deleteEvent(currentUser, ce.getId());
	}

	/**
	 * 检查是否能接收到分享
	 * 
	 * @param eventid
	 * @param uid
	 * @return
	 */
	public boolean checkSharedLimit(int eventid, int uid) {
		String query="select map.id from Sharemapping map where map.eventid="+eventid+" and (map.share2uid="+uid+" or map.share2uid=0)";
		List list=this.sharemappingDAO.findByQuery(query);
		if(list!=null&&list.size()>0)
			return true;
		else	
			return false;
	}

	/**
	 * 检查用户是否已选择不再提示
	 * 
	 * @param eventid
	 * @param uid
	 * @return
	 */
	public boolean checkIsShielded(int eventid, int uid) {
		String query="select map.id from Sharemapping map where map.eventid="+eventid+" and map.share2uid="+uid+" and map.acceptstatus=0";
		List list=this.sharemappingDAO.findByQuery(query);
		if(list!=null&&list.size()>0)
			return true;
		else	
			return false;
	}
	/**
	 * @param startdate
	 * @param currentUser
	 * @return
	 */
	public int countPrivateEventsByDay(Calendar startdate, User currentUser) {
		Calendar start=(Calendar) startdate.clone();
		start.clear(Calendar.MILLISECOND);
		start.clear(Calendar.SECOND);
		start.clear(Calendar.MINUTE);
		start.set(Calendar.HOUR_OF_DAY, 0);
		Calendar end=(Calendar) startdate.clone();
		end.add(Calendar.DAY_OF_MONTH, 1);
		String query="select count(*) from ClipEvent clip where clip.cliptype=1 and clip.status=1 and clip.uid="+currentUser.getId()+" and " +
		"((clip.begintime<="+start.getTimeInMillis()+" and clip.endtime>="+start.getTimeInMillis()+") or "+
		" (clip.begintime>"+start.getTimeInMillis()+" and clip.begintime<"+end.getTimeInMillis()+"))";
		return this.clipEventDao.countByQuery(query);
	}
	
	/**
	 * 找乐子档期，查找某日是否有找乐子档期
	 * @param startdate
	 * @param currentUser
	 * @return
	 */
	public int countOwnEventsByDay(Calendar startdate, User currentUser) {
		Calendar start=(Calendar) startdate.clone();
		start.clear(Calendar.MILLISECOND);
		start.clear(Calendar.SECOND);
		start.clear(Calendar.MINUTE);
		start.set(Calendar.HOUR_OF_DAY, 0);
		Calendar end=(Calendar) startdate.clone();
		end.add(Calendar.DAY_OF_MONTH, 1);
		String query="select count(*) from ClipEvent clip where (clip.cliptype=3 or clip.cliptype=4) and clip.status=1 and clip.uid="+currentUser.getId()+" and " +
		" ( "+
		"((clip.begintime<="+start.getTimeInMillis()+" and clip.endtime>="+start.getTimeInMillis()+") or "+
		" (clip.begintime>"+start.getTimeInMillis()+" and clip.begintime<"+end.getTimeInMillis()+"))"+
		"  or ("+
		" clip.invitetime>0 and clip.invitetime>="+start.getTimeInMillis()+" and clip.invitetime<"+end.getTimeInMillis()+
		" ) )";
		return this.clipEventDao.countByQuery(query);
	}

	public String getQueryContentAtCalendar(String queryby, User currentUser,Long lastquerycreattime, Calendar dateTime,String searchcontent) {
		boolean hasTime=false;
		boolean hasSearchContent=false;
		String clipeventtimequery=null;
		if(dateTime!=null){
			hasTime=true;
			Calendar firstDate=(Calendar) dateTime.clone();
			Calendar secondDate=(Calendar) firstDate.clone();
			secondDate.add(Calendar.DATE, 1);
			clipeventtimequery=" and (( ce.begintime<="+firstDate.getTimeInMillis()+" and ce.endtime>="+firstDate.getTimeInMillis()+" ) or  ( ce.begintime>"+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis()+" )) ";
		}
		if(searchcontent!=null){
			hasSearchContent=true;
		}
		StringBuffer sb=new StringBuffer();
		if(queryby.equals("own")){
			sb.append("ce.uid="+currentUser.getId()+" and (ce.cliptype=1 or ce.cliptype=3) and ce.clipstatus=1 ");
			if(hasTime)
				sb.append(clipeventtimequery);
			if(lastquerycreattime>0l){
				sb.append(" and ce.createtime<=");
				sb.append(lastquerycreattime);
			}
			if(hasSearchContent)
				sb.append(" and ce.title like '%"+searchcontent+"%' ");
		}else if(queryby.equals("share")){
			sb.append("exists (select s.id from shareevent as s where(s.share2uid=");
			sb.append(currentUser.getId());
			sb.append(" or exists(select c.id FROM contact as c where c.contactuid=");
			sb.append(currentUser.getId());
			sb.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0 )");
			sb.append(") and s.eventid=ce.id");
			sb.append(") and ce.cliptype=3 and ce.clipstatus=1 ");
			if(hasTime)
				sb.append(clipeventtimequery);
			if(lastquerycreattime>0l){
				sb.append(" and ce.createtime<=");
				sb.append(lastquerycreattime);
			}
			if(hasSearchContent)
				sb.append(" and ce.title like '%"+searchcontent+"%' ");
		}else if(queryby.equals("invite")){
			sb.append("ce.uid="+currentUser.getId());
			sb.append(" and (ce.cliptype=1 or ce.cliptype=3) and ce.reliedclip>0 and ce.clipstatus=0 and exists(select au.id from alertuser au where au.eventid=ce.reliedclip)");
			if(hasTime)
				sb.append(clipeventtimequery);
			if(hasSearchContent)
				sb.append(" and ce.title like '%"+searchcontent+"%' ");
		}else if(queryby.equals("alert")){
			sb.append("((ce.clipstatus=0 and ce.reliedclip>0) or ce.clipstatus=1) and ce.uid="+currentUser.getId());
			if(hasTime){
				Calendar firstDate=(Calendar) dateTime.clone();
				Calendar secondDate=(Calendar) firstDate.clone();
				secondDate.add(Calendar.DATE, 1);
				sb.append(" and ce.alerttime>="+firstDate.getTimeInMillis()+" and ce.alerttime<"+secondDate.getTimeInMillis());
			}else{
				sb.append(" and ce.alerttime>0");
			}
			if(hasSearchContent)
				sb.append(" and ce.title like '%"+searchcontent+"%' ");
//			if(hasSearchContent)
//				query.append(" and ce.title like '%"+content+"%' ");
//			query.append(" order by ce.createtime desc,ce.id desc");
		}
		return sb.toString();
	}

	public int getClipEventIdByPosition( String querycontent,int eventid,int move) {
		Object object=this.clipEventDao.uniqueResultByNamedQuery("getClipEventidByPosition", new Object[]{querycontent,eventid,move});
		if(object instanceof Integer){
			return (Integer)object;
		}else if(object instanceof BigInteger){
			return ((BigInteger)object).intValue();
		}else
			return 0;
	}

	public String getQueryContentAtClipPlaza(int contacttype, User currentUser,Long lastquerycreattime, Calendar dateTime) {
		Calendar firstDate=(Calendar) dateTime.clone();
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		String clipeventtimequery=" and (( ce.begintime<="+firstDate.getTimeInMillis()+" and ce.endtime>="+firstDate.getTimeInMillis()+" ) or  ( ce.begintime>"+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis()+" )) ";
		StringBuffer sb=new StringBuffer();
		sb.append("exists (select s.id from shareevent as s where ");
		if(contacttype==0)
			sb.append(" s.share2uid=0");
		else{
			sb.append(" (s.share2uid=");
			sb.append(currentUser.getId());
			sb.append(" or exists(select c.id FROM contact as c where c.contactuid=");
			sb.append(currentUser.getId());
			sb.append(" and c.status=1 and c.uid=s.uid and s.share2uid=0 )");
			sb.append(")"); 
		}
		sb.append(" and s.eventid=ce.id");
		sb.append(") and ce.cliptype=3 and ce.clipstatus=1 ");
		sb.append(clipeventtimequery);
		if(lastquerycreattime>0l){
			sb.append(" and ce.createtime<=");
			sb.append(lastquerycreattime);
		}
		return sb.toString();
	}

	public String getQueryContentAtClipUser(String visituid,int uid,Long lastquerycreatetime, Calendar dateTime) {
		Calendar firstDate=(Calendar) dateTime.clone();
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		String clipeventtimequery=" and (( ce.begintime<="+firstDate.getTimeInMillis()+" and ce.endtime>="+firstDate.getTimeInMillis()+" ) or  ( ce.begintime>"+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis()+" )) ";
		StringBuffer sb=new StringBuffer();
		sb.append("exists (select s.id from shareevent as s where ");
		sb.append(" (s.share2uid=0 or s.share2uid=");
		sb.append(uid);
		sb.append(" group by s.eventid ) and s.eventid=ce.id");
		sb.append(") and ce.cliptype=3 and ce.clipstatus=1 ");
		sb.append(clipeventtimequery);
		if(lastquerycreatetime>0l){
			sb.append(" and ce.createtime<=");
			sb.append(lastquerycreatetime);
		}
		return sb.toString();
	}

	public long countHasacceptInvitedEvents(User currentUser, Calendar datetime) {
		Calendar calendar=(Calendar) datetime.clone();
		calendar.add(Calendar.HOUR_OF_DAY, 24);
		return clipEventDao.countByNamedQuery("countHasacceptInviteEvents", new Object[]{currentUser.getId(),datetime.getTimeInMillis(),calendar.getTimeInMillis()});
	}

	public long countToInviteEvents(User currentUser, Calendar datetime) {
		Calendar calendar=(Calendar) datetime.clone();
		calendar.add(Calendar.HOUR_OF_DAY, 24);
		return clipEventDao.countByNamedQuery("countToInviteEvents", new Object[]{currentUser.getId(),datetime.getTimeInMillis(),calendar.getTimeInMillis()});
	}

	public List getSubscribeEvents(int uid, String ids, Calendar dateTime,long lastquerycreatetime, int currentpage,int pagesize) {
		Calendar firstDate=(Calendar) dateTime.clone();
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		StringBuffer sb=new StringBuffer();
		sb.append(" and (( ce.begintime<="+firstDate.getTimeInMillis()+" and ce.endtime>="+firstDate.getTimeInMillis()+" ) or  ( ce.begintime>"+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis()+" )) ");
		if(lastquerycreatetime>0l){
			sb.append(" and ce.createtime<=");
			sb.append(lastquerycreatetime);
		}
		return this.clipEventDao.findByNamedQuery("getSubscribeShareEvents",new Object[]{uid,ids,sb.toString()," order by ce.createtime desc",currentpage+1,pagesize});
	}

	public int countStartedSubscribeByDay(Calendar dateTime, int uid, String ids) {
		Calendar firstDate=(Calendar) dateTime.clone();
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer();
		query.append(" select count(distinct ce.id) from ClipEvent ce where "); 
		query.append(" ce.begintime>="+firstDate.getTimeInMillis()+" and ce.begintime<"+secondDate.getTimeInMillis());
		query.append(" and ce.uid in ("+ids+")");
		query.append(" and ce.seid=0 and ce.eventtype=2 and ce.cliptype=3 and ce.status=1");
		query.append(" and exists (select s.id from ShareEvent s where s.eventid=ce.id and (s.share2uid=0 or s.share2uid="+uid+"))");
		return this.clipEventDao.countByQuery(query.toString());
	}

	public int countEndedSubscribeByDay(Calendar dateTime, int uid, String ids) {
		Calendar firstDate=(Calendar) dateTime.clone();
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer();
		query.append(" select count(distinct ce.id) from ClipEvent ce where "); 
		query.append(" ce.begintime<"+firstDate.getTimeInMillis());
		query.append(" and ce.endtime>="+firstDate.getTimeInMillis()+" and ce.endtime<"+secondDate.getTimeInMillis());
		query.append(" and ce.iswholeday=0 ");
		query.append(" and ce.uid in ("+ids+")");
		query.append(" and ce.seid=0 and ce.eventtype=2 and ce.cliptype=3 and ce.status=1");
		query.append(" and exists (select s.id from ShareEvent s where s.eventid=ce.id and (s.share2uid=0 or s.share2uid="+uid+"))");
		return this.clipEventDao.countByQuery(query.toString());
	}

	/**
	 * @param uid
	 * @param eventid
	 * @return List<Integer>  uid
	 */
	public List findHaveInterestFriends(int uid, int eventid) {
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		String query="select map.uid from ShareAcceptmapping map where map.accepttype=1 and map.eventid=? and map.uid<>? and exists(select c.id from Contact c where c.uid=? and c.contactuid=map.uid and c.status=1) order by map.opttime desc";
		return this.shareacceptmappingDAO.findByQuery(query,new Object[]{eventid,uid,clipEvent.getUid()});
	}

	public List getEventInterests(int uid, int eventid,int currentpage,int pagelength) {
		ClipEvent ce=this.getDetailClipEvent(eventid);
		if(ce.getEventtype()==2){
			int dealeventid=0;
			if(ce.getSeid()==0){
				dealeventid=ce.getId();
			}else{
				dealeventid=ce.getSeid();
			}
			String query="select map.uid from ShareAcceptmapping map where map.accepttype=1 and map.eventid=? and map.uid<>? order by map.opttime desc";
			return this.shareacceptmappingDAO.pagingByQuery(query,currentpage,pagelength,new Object[]{dealeventid,uid});
		}else{
			return null;
		}
	}

	public List getEventFavors(int uid, int eventid, int currentpage,int pagelength) {
		ClipEvent ce=this.getDetailClipEvent(eventid);
		if(ce.getEventtype()==2){
			int dealeventid=0;
			if(ce.getSeid()==0){
				dealeventid=ce.getId();
			}else{
				dealeventid=ce.getSeid();
			}
			String query="select map.uid from ShareFavormapping map where map.eventid=? and map.uid<>? order by map.favortime desc";
			return this.sharefavormappingDAO.pagingByQuery(query,currentpage,pagelength,new Object[]{dealeventid,uid});
		}else{
			return null;
		}
	}

	public List getEventForwards(int uid, int eventid, int needpagenum,int forwardpagelength) {
		ClipEvent ce=this.getDetailClipEvent(eventid);
		int dealeventid=0;
		if(ce.getSeid()==0){
			dealeventid=ce.getId();
		}else{
			dealeventid=ce.getSeid();
		}
		String query="select map.uid from ShareAcceptmapping map where (map.accepttype=2 or map.accepttype=3) and map.eventid=? and map.uid<>? order by map.opttime desc";
		return this.shareacceptmappingDAO.findByQuery(query,new Object[]{dealeventid,uid});
	}

	/**
	 * @param eventid
	 * @return list 0 longitude
	 * 				1 latitude
	 */
	public List getEventLocation(int eventid) {
		String query="from ClipAddressref ref where ref.eventid=?";
		List list=this.addressrefDAO.findByQuery(query,new Object[]{eventid});
		List returnlist=new ArrayList();
		if(list!=null&&list.size()>0){
			ClipAddressref addressref=(ClipAddressref) list.get(0);
			returnlist.add(addressref.getLongitude());
			returnlist.add(addressref.getLatitude());
		}
		return returnlist;
	}

	public List searchEvent(String searchkey, int uid, int needpagenum,int pagelength) {
		String query="from ShareEvent se where (se.share2uid=0 or se.share2uid=?) and se.title like ? group by se.eventid order by se.createtime";
		return this.clipEventDao.pagingByQuery(query, needpagenum, pagelength,new Object[]{uid,"%"+searchkey+"%"});
	}

	public int countSearchEvent(String searchkey, int uid) {
		String query="select count(distinct se.eventid) from ShareEvent se where (se.share2uid=0 or se.share2uid=?) and se.title like ? ";
		return this.clipEventDao.countByQuery(query,new Object[]{uid,"%"+searchkey+"%"});
	}

	public void doFavorOnEvent(int uid, int eventid, int isfavor) {
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent.getEventtype()!=2)
			return;
		int dealeventid=0;
		if(clipEvent.getSeid()==0){
			dealeventid=clipEvent.getId();
		}else{
			dealeventid=clipEvent.getSeid();
		}
		Calendar now=Calendar.getInstance();
		if(isfavor==1){
			List list=this.sharefavormappingDAO.findByQuery("from ShareFavormapping map where map.eventid=? and map.uid=?",new Object[]{dealeventid,uid});
			if(list!=null&&list.size()>0){
				return;
			}else{
				ShareFavormapping favormapping=new ShareFavormapping();
				favormapping.setEventid(dealeventid);
				favormapping.setUid(uid);
				favormapping.setFavortime(Calendar.getInstance().getTimeInMillis());
				this.sharefavormappingDAO.save(favormapping);
			}
			addClipmessageEventMsg(dealeventid, uid, now, Clipmessage.FAVOREVENTTYPE, 0, false);
		}else{
			this.sharefavormappingDAO.excuteUpdateQuery("delete from ShareFavormapping map where map.eventid="+dealeventid+" and map.uid="+uid);
			removeClipmessageEventMsg(dealeventid, uid, Clipmessage.CANCELFAVOREVENTTYPE, false);
		}
		
		
		
	}

	/**
	 * @param eventid
	 * @param currentUser
	 * 
	 * 取消感兴趣的档期，如果是eventtype=2时，删除两条ShareAcceptmapping记录
	 */
	public void cancelInterest(int eventid, User currentUser) {
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent!=null&&clipEvent.getStatus()==1){
			int reliedclip=clipEvent.getReliedclip();
			if(clipEvent.getEventtype()==2&&clipEvent.getSeid()>0){
				ClipEvent rootEvent=null;
				rootEvent=this.getDetailClipEvent(clipEvent.getSeid());
				if(rootEvent==null||rootEvent.getStatus()!=1){
					throw new ClipEventNotExistException("");
				}
			}
			int usereventid=0;
			if(clipEvent.getEventtype()==2&&(clipEvent.getSeid()==0||clipEvent.getSeid().equals(clipEvent.getReliedclip()))){
				int dealeventid=0;
				if(clipEvent.getSeid()==0)
					dealeventid=clipEvent.getId();
				else
					dealeventid=clipEvent.getSeid();
				List acceptlist=this.shareacceptmappingDAO
					.findByQuery("from ShareAcceptmapping map where map.accepttype=1 and map.eventid=? and map.uid=?",new Object[]{dealeventid,currentUser.getId()});
				if(acceptlist!=null&&acceptlist.size()>0){
					ShareAcceptmapping shareAcceptmapping=(ShareAcceptmapping) acceptlist.get(0);
					usereventid=shareAcceptmapping.getFolloweventid();
					this.shareacceptmappingDAO.delete(shareAcceptmapping);//delete shareacceptmapping
					//弱关系一起删除，考虑到多个表态的存在，所以只删除当前档期的弱关系
					this.shareacceptmappingDAO.excuteUpdateQuery(
							" delete from ShareAcceptmapping map where map.accepttype=3 and map.eventid="+dealeventid+
							" and map.uid="+currentUser.getId()+
							" and map.followeventid="+usereventid
							);
				}else{
					throw new ClipEventNotExistException("");
				}
			}else{
				if(clipEvent.getEventtype()==2)
					//删除弱关系感兴趣
					this.shareacceptmappingDAO.excuteUpdateQuery("delete from ShareAcceptmapping map where map.accepttype=3 and map.eventid="+clipEvent.getSeid()+" and map.uid="+currentUser.getId());
				
				int dealeventid=0;
				if(clipEvent.getReliedclip()>0)
					dealeventid=clipEvent.getReliedclip();
				else
					dealeventid=clipEvent.getId();
				List acceptlist=this.shareacceptmappingDAO
					.findByQuery("from ShareAcceptmapping map where map.accepttype=1 and map.eventid=? and map.uid=?",new Object[]{dealeventid,currentUser.getId()});
				if(acceptlist!=null&&acceptlist.size()>0){
					ShareAcceptmapping shareAcceptmapping=(ShareAcceptmapping) acceptlist.get(0);
					usereventid=shareAcceptmapping.getFolloweventid();
					this.shareacceptmappingDAO.delete(shareAcceptmapping);//delete shareacceptmapping
				}else{
					throw new ClipEventNotExistException("");
				}
				
			}
			ClipEvent userEvent=this.getDetailClipEvent(usereventid);
			if(userEvent==null||userEvent.getStatus()!=1){
				throw new ClipEventNotExistException("");
			}
				
			String picdelquery="delete from ClipeventPic pic where pic.eventid="+userEvent.getId();
			this.clipeventPicDAO.excuteUpdateQuery(picdelquery);
			
			String addressdelquery="delete from ClipAddressref ref where ref.eventid="+userEvent.getId();
			this.addressrefDAO.excuteUpdateQuery(addressdelquery);
			
			this.clipEventDao.delete(userEvent);
			removeQuartz("clipevent_"+userEvent.getId());
			
			Calendar now=Calendar.getInstance();
			int addmsgeventid=0;
			if(clipEvent.getReliedclip()==0){
				addmsgeventid=clipEvent.getId();
			}else{
				addmsgeventid=clipEvent.getReliedclip();
			}
			if(clipEvent.getSeid()==0&&clipEvent.getEventtype()==2){
				removeClipmessageEventMsg(addmsgeventid,currentUser.getId(),Clipmessage.CANCELINTERESTEVENTTYPE,false);
			}else{
				removeClipmessageEventMsg(addmsgeventid,currentUser.getId(),Clipmessage.CANCELINTERESTEVENTTYPE,true);
			}
			
		}else{
			throw new ClipEventNotExistException("");
		}
	}
	//[public,private,memo,share]
	/**
	 * for APP
	 * @param year
	 * @param month
	 * @param date
	 * @param now
	 * @param currentUser
	 * @param querytype
	 * @param currentpage
	 * @param pagesize
	 * @return
	 */
	public List getEventsByDay(int year, int month, int date, Calendar now,	User currentUser, String querytype,int currentpage,int pagesize) {
		Calendar firstDateOfMonth=Calendar.getInstance();
		firstDateOfMonth.clear(Calendar.MILLISECOND);
		firstDateOfMonth.clear(Calendar.SECOND);
		firstDateOfMonth.clear(Calendar.MINUTE);
		firstDateOfMonth.set(Calendar.HOUR_OF_DAY,0);
		firstDateOfMonth.set(Calendar.YEAR, year);
		firstDateOfMonth.set(Calendar.MONTH, month);
		firstDateOfMonth.set(Calendar.DAY_OF_MONTH, date);
		Calendar lastDateOfMonth=(Calendar) firstDateOfMonth.clone();
		lastDateOfMonth.add(Calendar.DAY_OF_MONTH,+1);
		long begin=firstDateOfMonth.getTimeInMillis();
		long end=lastDateOfMonth.getTimeInMillis();
		if(querytype.equals("public")){
			String query="from ClipEvent clip where ((clip.begintime<="+begin+" and clip.endtime>="+begin+") or (clip.begintime>"+begin+" and clip.begintime<"+end+")) "+
					" and clip.cliptype=3 and clip.status=1 and clip.uid="+currentUser.getId()+
					" order by clip.createtime desc";
			return this.clipEventDao.pagingByQuery(query, currentpage, pagesize);
		}else if(querytype.equals("private")){
			String query="from ClipEvent clip where ((clip.begintime<="+begin+" and clip.endtime>="+begin+") or (clip.begintime>"+begin+" and clip.begintime<"+end+")) "+
					" and clip.cliptype=1 and clip.status!=2 and clip.uid="+currentUser.getId()+
					" order by clip.createtime desc";
			return this.clipEventDao.pagingByQuery(query, currentpage, pagesize);
		}else if(querytype.equals("memo")){
			SimpleDateFormat dateFormat=new SimpleDateFormat("MMdd");
			String query="from ClipEvent clip where clip.begintime<"+begin+" and clip.endtime="+"1"+dateFormat.format(firstDateOfMonth.getTime())+
					" and clip.cliptype=1 and clip.status!=2 and clip.uid="+currentUser.getId()+
					" order by clip.createtime desc";
			return this.clipEventDao.pagingByQuery(query, currentpage, pagesize);
		}else if(querytype.equals("share")){
			String query="from RequestEvent se where ((se.begintime<="+begin+" and se.endtime>="+begin+") or (se.begintime>"+begin+" and se.begintime<"+end+")) "+
					" and se.share2uid="+currentUser.getId()+
					" order by se.createtime desc";
			return this.clipEventDao.pagingByQuery(query, currentpage, pagesize);
		}else if(querytype.equals("own")){
			String query="from ClipEvent clip where (((clip.begintime<="+begin+" and clip.endtime>="+begin+") or (clip.begintime>"+begin+" and clip.begintime<"+end+")) "+
			" or (clip.invitetime>0 and clip.invitetime>="+begin+" and clip.invitetime<"+end+
			" )) "+
			" and (clip.cliptype=3 or clip.cliptype=4) and clip.status=1 and clip.uid="+currentUser.getId()+
			" order by clip.createtime desc";
			return this.clipEventDao.pagingByQuery(query, currentpage, pagesize);
		}else
			return null;
	}
	//[public,private,memo,share]
	public int countsEventsByDay(int year, int month, int date, int uid, String querytype) {
		Calendar firstDateOfMonth=Calendar.getInstance();
		firstDateOfMonth.clear(Calendar.MILLISECOND);
		firstDateOfMonth.clear(Calendar.SECOND);
		firstDateOfMonth.clear(Calendar.MINUTE);
		firstDateOfMonth.set(Calendar.HOUR_OF_DAY,0);
		firstDateOfMonth.set(Calendar.YEAR, year);
		firstDateOfMonth.set(Calendar.MONTH, month);
		firstDateOfMonth.set(Calendar.DAY_OF_MONTH, date);
		Calendar lastDateOfMonth=(Calendar) firstDateOfMonth.clone();
		lastDateOfMonth.add(Calendar.DAY_OF_MONTH,+1);
		long begin=firstDateOfMonth.getTimeInMillis();
		long end=firstDateOfMonth.getTimeInMillis();
		if(querytype.equals("public")){
			String query="select count(*) from ClipEvent clip where ((clip.begintime<="+begin+" and clip.endtime>="+begin+") or (clip.begintime>"+begin+" and clip.begintime<"+end+")) "+
					" and clip.cliptype=3 and clip.status=1 and clip.uid="+uid;
			return this.clipEventDao.countByQuery(query);
		}else if(querytype.equals("private")){
			String query="select count(*) from ClipEvent clip where ((clip.begintime<="+begin+" and clip.endtime>="+begin+") or (clip.begintime>"+begin+" and clip.begintime<"+end+")) "+
					" and clip.cliptype=1 and clip.status!=2 and clip.uid="+uid;
			return this.clipEventDao.countByQuery(query);
		}else if(querytype.equals("memo")){
			SimpleDateFormat dateFormat=new SimpleDateFormat("MMdd");
			String query="select count(*) from ClipEvent clip where clip.begintime<"+begin+" and clip.endtime="+"1"+dateFormat.format(firstDateOfMonth.getTime())+
					" and clip.cliptype=1 and clip.status!=2 and clip.uid="+uid;
			return this.clipEventDao.countByQuery(query);
		}else if(querytype.equals("share")){
			String query="select count(*) from RequestEvent se where ((se.begintime<="+begin+" and se.endtime>="+begin+") or (se.begintime>"+begin+" and se.begintime<"+end+")) "+
					" and se.share2uid="+uid;
			return this.clipEventDao.countByQuery(query);
		}else if(querytype.equals("own")){
			String query="select count(*) from ClipEvent clip where (((clip.begintime<="+begin+" and clip.endtime>="+begin+") or (clip.begintime>"+begin+" and clip.begintime<"+end+")) "+
			" or ( clip.invitetime>0 and clip.invitetime>="+begin+" and clip.invitetime<"+end+
			" )) "+
			" and (clip.cliptype=3 or clip.cliptype=4) and clip.status=1 and clip.uid="+uid;
			return this.clipEventDao.countByQuery(query);
		}else
			return 0;
	}

	public int countsUserEventsByDay(int year, int month, int date, int currentuid, int vuid) {
		Calendar firstDateOfMonth=Calendar.getInstance();
		firstDateOfMonth.clear(Calendar.MILLISECOND);
		firstDateOfMonth.clear(Calendar.SECOND);
		firstDateOfMonth.clear(Calendar.MINUTE);
		firstDateOfMonth.set(Calendar.HOUR_OF_DAY,0);
		firstDateOfMonth.set(Calendar.YEAR, year);
		firstDateOfMonth.set(Calendar.MONTH, month);
		firstDateOfMonth.set(Calendar.DAY_OF_MONTH, date);
		Calendar lastDateOfMonth=(Calendar) firstDateOfMonth.clone();
		lastDateOfMonth.add(Calendar.DAY_OF_MONTH,+1);
		long begin=firstDateOfMonth.getTimeInMillis();
		long end=firstDateOfMonth.getTimeInMillis();
		String query="select count(*) from ShareEvent se where ((se.begintime<="+begin+" and se.endtime>="+begin+") or (se.begintime>"+begin+" and se.begintime<"+end+")) "+
		" and se.uid="+vuid+" and se.share2uid="+currentuid;
		return this.clipEventDao.countByQuery(query);
	}
	
	
	public int addInterestsInvite(User currentUser, int seid, long alerttime,int mobilenotice, long deadlinetime, String contactlist) {
		ClipEvent sourceEvent=this.clipEventDao.findById(seid);
		if(sourceEvent!=null&&sourceEvent.getStatus()==1){
			Calendar now=Calendar.getInstance();
			ClipEvent clipEvent=(ClipEvent) sourceEvent.clone();
			clipEvent.setUid(currentUser.getId());
			clipEvent.setSeid(sourceEvent.getId());
			clipEvent.setAlerttime(alerttime);
			clipEvent.setMobilenotice(mobilenotice);
//			clipEvent.setDeadlinetime(deadlinetime);
			clipEvent.setCliptype(1);
			clipEvent.setCreatetime(now.getTimeInMillis());
			clipEvent.setStatus(1);
			clipEvent.setShareid("");
			clipEvent.setProcessstatus(0);
			clipEvent.setIsread(1);
			this.clipEventDao.save(clipEvent);
			
			List addressList=this.addressrefDAO.findByQuery("from ClipAddressref ref where ref.eventid=?", new Object[]{sourceEvent.getId()});
			if(addressList!=null&&addressList.size()>0){
				ClipAddressref ref=(ClipAddressref) addressList.get(0);
				ClipAddressref refnew=new ClipAddressref();
				refnew.setEventid(clipEvent.getId());
				refnew.setLatitude(ref.getLatitude());
				refnew.setLongitude(ref.getLongitude());
				this.addressrefDAO.save(refnew);
			}
			List picList=this.clipeventPicDAO.findByQuery("from ClipeventPic pic where pic.eventid=?", new Object[]{sourceEvent.getId()});
			if(picList!=null&&picList.size()>0){
				ClipeventPic pic=(ClipeventPic) picList.get(0);
				ClipeventPic picnew=new ClipeventPic();
				picnew.setEventid(clipEvent.getId());
				this.clipeventPicDAO.save(picnew);
			}
			ShareAcceptmapping acceptmapping=new ShareAcceptmapping();
			acceptmapping.setAccepttype(4);
			acceptmapping.setEventid(sourceEvent.getId());
			acceptmapping.setFolloweventid(clipEvent.getId());
			acceptmapping.setOpttime(now.getTimeInMillis());
			acceptmapping.setUid(currentUser.getId());
			this.shareacceptmappingDAO.save(acceptmapping);
			
			saveContactList(clipEvent,currentUser,contactlist,"",true);
			
			addClipEventClock(alerttime,clipEvent,mobilenotice);
			return clipEvent.getId();
			
		}else
			return 0;
	}

	/**
	 * @param clipEvent
	 * @param currentUser
	 * @return index 	0: interestcount
	 * 					1: favorcount
	 */
	public List<Long> checkUserStatusAboutShareEvent(ClipEvent clipEvent,	User currentUser) {
		List<Long> list=new ArrayList<Long>();
		String sql=null;
		sql="from ShareAcceptmapping map where map.eventid=? and map.uid=? and map.accepttype=1";
		if(clipEvent.getEventtype()==2){
			List interestlist=null;
			String favorsql=null;
			//表示查看的是商家的界面  
			if(clipEvent.getSeid()==0&&clipEvent.getReliedclip()==0){
				interestlist=this.shareacceptmappingDAO.findByQuery(sql, new Object[]{clipEvent.getId(),currentUser.getId()});
				favorsql="select count(*) from ShareFavormapping map where map.eventid="+clipEvent.getId()+" and map.uid="+currentUser.getId();
			}else{
				interestlist=this.shareacceptmappingDAO.findByQuery(sql, new Object[]{clipEvent.getSeid(),currentUser.getId()});
				favorsql="select count(*) from ShareFavormapping map where map.eventid="+clipEvent.getSeid()+" and map.uid="+currentUser.getId();
			}
			if(interestlist!=null&&interestlist.size()>0){
				list.add(1l);
			}else{
				list.add(0l);
			}
			Long favorcount=(Long) this.sharefavormappingDAO.countByQuery(favorsql);
			favorcount=favorcount>0l?1l:0l;
			list.add(favorcount);
		}else{
			//对于发起人(个人)的表态
			List interestlist=null;
			//表示查看的是商家的界面  
			interestlist=this.shareacceptmappingDAO.findByQuery(sql, new Object[]{clipEvent.getId(),currentUser.getId()});
			if(interestlist!=null&&interestlist.size()>0){
				list.add(1l);
			}else{
				list.add(0l);
			}
		}
		return list;
	}

//	public ClipEvent launchInviteclipFromShare(User currentUser, int eventid,String contactlist,long alerttime,long deadlinetime) {
//		ClipEvent clipEvent=getDetailClipEvent(eventid);
//		if(clipEvent==null||clipEvent.getStatus()!=1){
//			return null;
//		}
//		Calendar now=Calendar.getInstance();
//		ClipEvent newEvent=(ClipEvent) clipEvent.clone();
//		newEvent.setId(0);
//		newEvent.setAlerttime(alerttime);
////		newEvent.setDeadlinetime(deadlinetime);
//		newEvent.setCreatetime(now.getTimeInMillis());
//		newEvent.setSeid(eventid);
//		newEvent.setUid(currentUser.getId());
//		newEvent.setReliedclip(0);
//		this.clipEventDao.save(newEvent);
//		cloneClipeventPic(eventid,newEvent.getId());
//		cloneClipAddressref(eventid,newEvent.getId());
//		ShareAcceptmapping acceptmapping=new ShareAcceptmapping();
//		acceptmapping.setAccepttype(ShareAcceptmapping.JOINTYPE);
//		acceptmapping.setEventid(eventid);
//		acceptmapping.setFolloweventid(newEvent.getId());
//		acceptmapping.setOpttime(now.getTimeInMillis());
//		acceptmapping.setUid(currentUser.getId());
//		this.shareacceptmappingDAO.save(acceptmapping);
//		saveContactList(clipEvent,currentUser,contactlist,"",true);
//		addClipEventClock(alerttime,clipEvent,0);
//		return newEvent;
//	}

//	public ClipEvent addCliptype(User currentUser, int eventid, int cliptype,String contactlist, long deadlinetime, String sharelist,String share2userlist) {
//		ClipEvent clipEvent=getDetailClipEvent(eventid);
//		if(clipEvent==null||clipEvent.getStatus()!=1){
//			return null;
//		}
//		Calendar now=Calendar.getInstance();
//		clipEvent.setCliptype(cliptype);
//		if(cliptype==1){
////			clipEvent.setDeadlinetime(deadlinetime);
//			saveContactList(clipEvent,currentUser,contactlist,"",true);
//		}else if(cliptype==3){
//			 if(share2userlist!=null&&share2userlist.length()>0){
//				saveShare2userList(clipEvent,share2userlist);
//			}
//		}
//		clipEvent.setCreatetime(now.getTimeInMillis());
//		this.clipEventDao.attachDirty(clipEvent);
//		return clipEvent;
//	}

	public int countSubscribeByDay(User currentUser,Calendar startdate) {
		String querycc="select u.id from User u, Contact c where u.usertype=2 and u.status=1 and c.uid=u.id and c.contacttypeid=2 and c.status=1 and c.contactuid=? order by c.createtime";
		List list=this.userDAO.findByQuery(querycc,new Object[]{currentUser.getId()});
		String ids=null;
		if(list!=null&&list.size()>0){
			for (int i=0;i<list.size();i++){
				Integer uid=(Integer) list.get(i);
				if(i==0){
					ids=uid.toString();
				}else{
					ids+=","+uid.toString();
				}
				
			}
		}
		Calendar enddate=(Calendar) startdate.clone();
		enddate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer("select count(distinct s.id) from ClipEvent s where ");
		query.append(" ((s.begintime<="+startdate.getTimeInMillis()+" and s.endtime>="+startdate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+startdate.getTimeInMillis()+" and s.begintime<"+enddate.getTimeInMillis()+"))");
		query.append(" and s.seid=0 and s.eventtype=2 and s.reliedclip=0 ");
		if(ids!=null&&ids.length()>0){
			query.append(" and s.uid in ("+ids+")");
		}
		int resultcount=this.clipEventDao.countByQuery(query.toString());
		//在这里可以添加推荐档期的数量
		return resultcount;
	}

	/**
	 * 此方法对于推荐档期的加入，还需进行修改
	 * @param currentUser
	 * @param dateTime
	 * @param currentpage
	 * @param pagesize
	 * @return
	 */
	public List getAllSubscribeEvents(User currentUser,Calendar dateTime,int currentpage, int pagesize) {
		String querycc="select u.id from User u, Contact c where u.usertype=2 and u.status=1 and c.uid=u.id and c.contacttypeid=2 and c.status=1 and c.contactuid=? order by c.createtime";
		List list=this.userDAO.findByQuery(querycc,new Object[]{currentUser.getId()});
		String ids=null;
		if(list!=null&&list.size()>0){
			for (int i=0;i<list.size();i++){
				Integer uid=(Integer) list.get(i);
				if(i==0){
					ids=uid.toString();
				}else{
					ids+=","+uid.toString();
				}
				
			}
		}
		Calendar firstDate=(Calendar) dateTime.clone();
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer("from ShareEvent s where ");
		query.append(" ((s.begintime<="+firstDate.getTimeInMillis()+" and s.endtime>="+firstDate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+firstDate.getTimeInMillis()+" and s.begintime<"+secondDate.getTimeInMillis()+"))");
		query.append(" and s.share2uid=0 and s.eventtype=2 and s.reliedclip=0 ");
		if(ids!=null&&ids.length()>0){
			query.append(" and s.uid in ("+ids+") ");
		}
		query.append(" group by s.eventid order by s.createtime");
		return this.clipEventDao.pagingByQuery(query.toString(), currentpage, pagesize);
	}

	public String getEventTitle(int eventid) {
		ClipEvent ce=this.clipEventDao.findById(eventid);
		if(ce==null){
			return null;
		}else{
			return ce.getTitle();
		}
	}

	public List getUsersShareEventsByDay(int year, int month, int date,
			int vuid,User currentUser, Long lastquerycreattime,int lastcurrentpage,int pagelength) {
		Calendar firstDate=Calendar.getInstance();
		firstDate.clear(Calendar.MILLISECOND);
		firstDate.clear(Calendar.SECOND);
		firstDate.clear(Calendar.MINUTE);
		firstDate.set(Calendar.HOUR_OF_DAY, 0);
		firstDate.set(Calendar.YEAR, year);
		firstDate.set(Calendar.MONTH, month);
		firstDate.set(Calendar.DAY_OF_MONTH,date);
		Calendar secondDate=(Calendar) firstDate.clone();
		secondDate.add(Calendar.DATE, 1);
		StringBuffer query=new StringBuffer("from ShareEvent s where ");
		query.append(" ((s.begintime<="+firstDate.getTimeInMillis()+" and s.endtime>="+firstDate.getTimeInMillis()+") or ");
		query.append("  (s.begintime>"+firstDate.getTimeInMillis()+" and s.begintime<"+secondDate.getTimeInMillis()+"))");
		if(currentUser.getId()!=vuid)
			query.append(" and  s.share2uid="+currentUser.getId());
		query.append(" and s.uid=");
		if(vuid==0)
			query.append(currentUser.getId());
		else
			query.append(vuid);
		
		if(lastquerycreattime>0l){
			query.append(" and s.createtime<=");
			query.append(lastquerycreattime);
		}
		
		query.append(" group by s.eventid  order by s.createtime desc");
		List list=null;
			list=this.clipEventDao.pagingByQuery(query.toString(),lastcurrentpage+1,pagelength);
		return list;
	}

	public List getSubscribeEventList(int ccuid, int currentpage,int pagelength) {
		String sql="from ClipEvent ce where ce.cliptype=3 and ce.reliedclip=0 and ce.uid="+ccuid;
		return this.clipEventDao.pagingByQuery(sql, currentpage, pagelength);
	}

	public boolean confirmEvent(int eventid, User currentUser,String share2userlist) {
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent!=null&&clipEvent.getUid()==currentUser.getId()){
			List list=new ArrayList();//share2uid
			List<Contact> contactList=new ArrayList<Contact>();
			if(share2userlist!=null&&share2userlist.length()>0){
				if(share2userlist.indexOf(",")>0){
					String[] uids=share2userlist.split(",");
					for (String suid : uids) {
						int uid=Integer.parseInt(suid);
						list.add(uid);
					}
				}else{
					list.add(Integer.parseInt(share2userlist));
				}
				for (Object object : list) {
					int share2uid=(Integer)object;
					List temp=this.contactDAO.findByQuery("from Contact c where c.uid=? and c.contactuid=? and c.status=1", new Object[]{currentUser.getId(),share2uid});
					if(temp!=null&&temp.size()>0){
						Contact contact=(Contact) temp.get(0);
						contactList.add(contact);
					}
				}
			}else{
				String shareAcceptMappingSql="from ShareAcceptmapping map where map.eventid=? and map.accepttype=1";
				List shareAcceptMappingList=this.shareacceptmappingDAO.findByQuery(shareAcceptMappingSql, new Object[]{eventid});
				StringBuffer uidstr=new StringBuffer();
				for (Object object : shareAcceptMappingList) {
					ShareAcceptmapping acceptmapping=(ShareAcceptmapping) object;
					int share2uid=acceptmapping.getUid();
					List temp=this.contactDAO.findByQuery("from Contact c where c.uid=? and c.contactuid=? and c.status=1", new Object[]{currentUser.getId(),share2uid});
					if(temp!=null&&temp.size()>0){
						Contact contact=(Contact) temp.get(0);
						contactList.add(contact);
					}
					if(uidstr.length()>0){
						uidstr.append(",");
					}
					uidstr.append(share2uid);
				}
				this.sharemappingDAO.excuteUpdateQuery("delete from Sharemapping map where map.eventid="+eventid+" and map.share2uid not in ("+uidstr.toString()+")");
				
			}
			
			if(clipEvent.getSeid()>0&&clipEvent.getEventtype()==2){
				Calendar now=Calendar.getInstance();
				ShareAcceptmapping acceptmapping=new ShareAcceptmapping();
				acceptmapping.setAccepttype(ShareAcceptmapping.WEAKINTERESTYYPE);
				acceptmapping.setEventid(clipEvent.getSeid());
				acceptmapping.setFolloweventid(clipEvent.getId());
				acceptmapping.setOpttime(now.getTimeInMillis());
				acceptmapping.setUid(currentUser.getId());
				this.shareacceptmappingDAO.save(acceptmapping);
			}
			
			for (Contact contact : contactList) {
				int contactuid=contact.getContactuid();
				String temp="select event.id from ClipEvent event where event.uid=? and event.reliedclip=? and event.status=1";
				List templist=this.clipEventDao.findByQuery(temp, new Object[]{contactuid,eventid});
				Integer followclipid=(Integer) templist.get(0);
				AlertUser alertUser=new AlertUser();
				alertUser.setEventid(clipEvent.getId());
				alertUser.setUid(currentUser.getId());
				alertUser.setContactid(contact.getId());
				alertUser.setContactuid(contact.getContactuid());
				alertUser.setMobilenotice(0);
				alertUser.setStatus(1);
				alertUser.setFolloweventid(followclipid);
				sendConfirmEventEmail(currentUser, clipEvent,contact.getContactuid());
				alertUserDAO.save(alertUser);
			}
			
			addClipmessageEventMsg(eventid, currentUser.getId(), Calendar.getInstance(), Clipmessage.CONFIRMEVENTTYPE, 0, true);
			
			return true;
		}else
			return false;
	}

	private void sendConfirmEventEmail(User publisher, ClipEvent clipEvent,int toinformeduid) {
		User alertUser=this.userDAO.findById(toinformeduid);
		String url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/clip_detail.html?"+clipEvent.getShareid();
		List<UserEmail> userEmails=userEmailDAO.findByQuery("from UserEmail ue where ue.bindable=1 and ue.status=1 and ue.uid="+toinformeduid);
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("pname", publisher.getName());
		root.put("fname", alertUser.getName());
		root.put("title", clipEvent.getTitle());
		root.put("url", url);
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"confirmevent.ftl");
		for (UserEmail userEmail : userEmails) {
			SimpleMailSender.send(mailcontent, alertUser.getName()+"，你有一个来自档期的消息", userEmail.getEmail());
		}
	}
	
	public String controlMessageWithClipevent(int uid, int eventid,int acceptstatus) {
		String querySharemappingSQL="from Sharemapping map where map.eventid=? and map.share2uid=?";
		List list=this.sharemappingDAO.findByQuery(querySharemappingSQL,new Object[]{eventid,uid});
		if(list==null||list.size()==0){
			return "数据错误";
		}else{
			Sharemapping map=(Sharemapping) list.get(0);
			map.setContacttypeid(acceptstatus);
			this.sharemappingDAO.attachDirty(map);
			return null;
		}
	}

	/**
	 * @param eventid
	 * @param uid
	 * @return 	>0	表示感兴趣
	 * 			0	表示还未表态
	 */
	public int getInviteEventInterestORNOT(Integer eventid, int uid) {
		String queryShareAcceptmappingSQL="from ShareAcceptmapping accept where accept.eventid=? and accept.uid=? and accept.accepttype=1";
		List list=this.shareacceptmappingDAO.findByQuery(queryShareAcceptmappingSQL, new Object[]{eventid,uid});
		if(list!=null&&list.size()>0){
			ShareAcceptmapping acceptmapping=(ShareAcceptmapping) list.get(0);
			return acceptmapping.getFolloweventid();
		}else
			return 0;
	}

	public List getShare2users(Integer eventid) {
		String querySharemappingSQL="from Sharemapping map where map.eventid=?";
		List list=this.sharemappingDAO.findByQuery(querySharemappingSQL,new Object[]{eventid});
		return list;
	}

	public ClipeventPic getClipeventPic(int eventid) {
		List list=this.clipeventPicDAO.findByQuery("from ClipeventPic pic where pic.eventid=?", new Object[]{eventid});
		if(list!=null&&list.size()==1){
			return (ClipeventPic) list.get(0);
		}else
			return null;
	}

	public void quitClip(int eventid, User currentUser) {
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent!=null&&clipEvent.getStatus()==1){
			int reliedclip=clipEvent.getReliedclip();
			ClipEvent rootEvent=null;
			if(reliedclip>0){
				rootEvent=this.getDetailClipEvent(reliedclip);
				if(rootEvent==null||rootEvent.getStatus()!=1){
					throw new ClipEventNotExistException("");
				}
			}else{
				rootEvent=clipEvent;
			}
			List acceptlist=this.shareacceptmappingDAO.findByQuery("from ShareAcceptmapping map where map.accepttype=1 and map.eventid=? and map.uid=?",new Object[]{rootEvent.getId(),currentUser.getId()});
			if(acceptlist!=null&&acceptlist.size()>0){
				ShareAcceptmapping shareAcceptmapping=(ShareAcceptmapping) acceptlist.get(0);
				int usereventid=shareAcceptmapping.getFolloweventid();
				this.shareacceptmappingDAO.delete(shareAcceptmapping);//delete shareacceptmapping
				ClipEvent userEvent=this.getDetailClipEvent(usereventid);
				
//				String sharemappingquery="delete from Sharemapping map where map.eventid="+userEvent.getId();
//				this.sharemappingDAO.excuteUpdateQuery(sharemappingquery);//delete sharemapping
				
				String picdelquery="delete from ClipeventPic pic where pic.eventid="+userEvent.getId();
				this.clipeventPicDAO.excuteUpdateQuery(picdelquery);
				
				String addressdelquery="delete from ClipAddressref ref where ref.eventid="+userEvent.getId();
				this.addressrefDAO.excuteUpdateQuery(addressdelquery);
				
				
				String alertUserSql="delete from AlertUser au where au.eventid="+rootEvent.getId()+" and au.contactuid="+currentUser.getId();
				this.alertUserDAO.excuteUpdateQuery(alertUserSql);
				
				this.clipEventDao.delete(userEvent);
				removeQuartz("clipevent_"+userEvent.getId());
				
				Calendar now=Calendar.getInstance();
				int addmsgeventid=0;
				if(clipEvent.getReliedclip()==0){
					addmsgeventid=clipEvent.getId();
				}else{
					addmsgeventid=clipEvent.getReliedclip();
				}
				sendQuitclipEmail(rootEvent.getUid(),rootEvent,currentUser);
				if(clipEvent.getSeid()==0&&clipEvent.getEventtype()==2){
					//不可能
					addClipmessageEventMsg(addmsgeventid,currentUser.getId(),now,Clipmessage.QUITEVENTTYPE,reliedclip,false);
				}else{
					addClipmessageEventMsg(addmsgeventid,currentUser.getId(),now,Clipmessage.QUITEVENTTYPE,reliedclip,true);
				}
			}else{
				throw new ClipEventNotExistException("");
			}
		}else{
			throw new ClipEventNotExistException("");
		}
	}
	
	private void sendQuitclipEmail(int pubuid, ClipEvent clipEvent,User currentUser){
		User alertUser=this.userDAO.findById(pubuid);
		String url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/clip_detail.html?"+clipEvent.getShareid();
		List<UserEmail> userEmails=userEmailDAO.findByQuery("from UserEmail ue where ue.bindable=1 and ue.status=1 and ue.uid="+alertUser.getId());
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("currentuname", currentUser.getName());
		root.put("funame", alertUser.getName());
		root.put("title", clipEvent.getTitle());
		root.put("url", url);
		String mailcontent = com.clip.util.FtlUtils.stringRender(root,"quitclip.ftl");
		for (UserEmail userEmail : userEmails) {
			SimpleMailSender.send(mailcontent, alertUser.getName()+"，你有一个来自档期的消息", userEmail.getEmail());
		}
	
		
	}

	public boolean shieldClipmessage(Integer eventid, User currentUser,boolean isshield) {
		ClipEvent clipEvent=this.getDetailClipEvent(eventid);
		if(clipEvent!=null&&clipEvent.getStatus()==1){
			String sharemappingSql="from Sharemapping map where map.eventid=? and map.share2uid=?";
			List list=this.sharemappingDAO.findByQuery(sharemappingSql, new Object[]{eventid,currentUser.getId()});
			if(list!=null&&list.size()==1){
				Sharemapping sharemapping=(Sharemapping) list.get(0);
				if(isshield)
					sharemapping.setAcceptstatus(0);
				else
					sharemapping.setAcceptstatus(1);
				this.sharemappingDAO.attachDirty(sharemapping);
				return true;
			}else
				return false;
		}else
			return false;
	}

	public List getDetailStatAboutClipEvent(ClipEvent clipEvent,User currentUser) {
		List list=new ArrayList();
		int parentid=clipEvent.getReliedclip();
		String sql=null;
		int counteventid=0;
		if(parentid>0){
			counteventid=parentid;
		}else{
			counteventid=clipEvent.getId();
		}
		if(clipEvent.getCliptype()==3){
			//eventtype==2 seid==0 eventuid==currentuseruid
			if(currentUser.getUsertype()==2){
				//商家查看自己发起的档期
				sql="select count(*) from ShareAcceptmapping map where (map.accepttype=1 or map.accepttype=3)  and map.eventid="+clipEvent.getId();
				Long interestcount=(Long) this.shareacceptmappingDAO.countByQuery(sql);
				list.add(interestcount);
				sql="select count(*) from ShareAcceptmapping map where map.accepttype=2  and map.eventid="+clipEvent.getId();
				Long forwardcount=(Long) this.shareacceptmappingDAO.countByQuery(sql);
				list.add(forwardcount);
				sql="select count(*) from ShareFavormapping map where map.eventid="+clipEvent.getId();
				Long favorcount=(Long) this.sharefavormappingDAO.countByQuery(sql);
				list.add(favorcount);
			}else{
				if(clipEvent.getEventtype()==2&&(clipEvent.getSeid()==0||clipEvent.getSeid().equals(clipEvent.getReliedclip()))){
					//直接看商家/查看自己直接感兴趣的商家档期
					if(clipEvent.getSeid()==0)
						sql="select count(*) from ShareAcceptmapping map where map.accepttype=1  and map.eventid="+clipEvent.getId();
					else
						sql="select count(*) from ShareAcceptmapping map where map.accepttype=1  and map.eventid="+clipEvent.getSeid();	
					Long interestcount=(Long) this.shareacceptmappingDAO.countByQuery(sql);
					list.add(interestcount);
					if(clipEvent.getSeid()==0)
						sql="select count(*) from ShareAcceptmapping map where map.accepttype=2  and map.eventid="+clipEvent.getId();
					else
						sql="select count(*) from ShareAcceptmapping map where map.accepttype=2  and map.eventid="+clipEvent.getSeid();	
					Long forwardcount=(Long) this.shareacceptmappingDAO.countByQuery(sql);
					list.add(forwardcount);
					if(clipEvent.getSeid()==0)
						sql="select count(*) from ShareFavormapping map where map.eventid="+clipEvent.getId();
					else
						sql="select count(*) from ShareFavormapping map where map.eventid="+clipEvent.getSeid();	
					Long favorcount=(Long) this.sharefavormappingDAO.countByQuery(sql);
					list.add(favorcount);
				}
			}
			sql="select count(*) from Clipmessage msg where msg.eventid="+counteventid;
			Long msgcount=(Long) this.clipmessageDAO.countByQuery(sql);
			list.add(msgcount);
		}else if(clipEvent.getCliptype()==4){
			sql="select count(*) from Clipmessage msg where msg.eventid="+clipEvent.getId();
			Long msgcount=(Long) this.clipmessageDAO.countByQuery(sql);
			list.add(msgcount);
		}
		return list;
	}

	public List<Integer> loadPagingInterestUsers(Integer eventid,User currentUser, int currentpage,int pagelength) {
		String sql=null;
		if(currentUser.getUsertype()==2)
			sql="select distinct(map.uid) from ShareAcceptmapping map where (map.accepttype=1 or map.accepttype=3) and map.eventid="+eventid+" order by map.opttime desc";
		else
			sql="select distinct(map.uid) from ShareAcceptmapping map where map.accepttype=1 and map.eventid="+eventid+" order by map.opttime desc";
		return this.shareacceptmappingDAO.pagingByQuery(sql, currentpage, pagelength);
	}

	public List<Integer> loadPagingForwardUsers(Integer eventid, int currentpage,int pagelength) {
		String sql=null;
		sql="select distinct(map.uid) from ShareAcceptmapping map where map.accepttype=2 and map.eventid="+eventid+" order by map.opttime desc";
		return this.shareacceptmappingDAO.pagingByQuery(sql, currentpage, pagelength);
	}

	public List<Integer> loadPagingFavorUsers(Integer eventid, int currentpage,int pagelength) {
		String sql=null;
		sql="select distinct(map.uid) from ShareFavormapping map where map.eventid="+eventid+" order by map.favortime desc";
		return this.shareacceptmappingDAO.pagingByQuery(sql, currentpage, pagelength);
	}
	
	public List<Integer> getPagingShareInfo(Integer eventid, User currentUser,String pageclass,int currentpage,int pagelength) {
		if(pageclass.equals(this.PAGE_INTERESTCLASS)){
			String accepttypesql=null;
			if(currentUser.getUsertype()==2){
				accepttypesql=" (map.accepttype=1 or map.accepttype=3) ";
			}else{
				accepttypesql=" map.accepttype=1 ";
			}
			String sql="select distinct(map.uid) from ShareAcceptmapping map where "+accepttypesql+" and map.eventid="+eventid+" order by map.opttime desc";
			return this.shareacceptmappingDAO.pagingByQuery(sql, currentpage, pagelength);
		}else if(pageclass.equals(this.PAGE_FORWARDCLASS)){
			return loadPagingForwardUsers(eventid,currentpage,pagelength);
		}else if(pageclass.equals(this.PAGE_FAVORCLASS)){
			return loadPagingFavorUsers(eventid,currentpage,pagelength);
		}
		return null;
	}
	
	public boolean checkIsshare2user(Integer eventid, int uid) {
		String sql="select map.id from Sharemapping map where map.eventid="+eventid+" and map.share2uid="+uid;
		List list=this.sharemappingDAO.findByQuery(sql);
		if(list!=null&&list.size()==1){
			return true;
		}else
			return false;
	}
	
	public boolean checkClipEventForwardedORNOT(Integer eventid, int uid) {
		boolean result=false;
		String sql="select map.id from ShareAcceptmapping map where map.eventid=? and map.uid=? and map.accepttype=2";
		List list=this.shareacceptmappingDAO.findByQuery(sql, new Object[]{eventid,uid});
		if(list!=null&&list.size()>0){
			result=true;
		}
		return result;
	}
	private final String PAGE_INTERESTCLASS="interest";
	private final String PAGE_FORWARDCLASS="forward";
	private final String PAGE_FAVORCLASS="favor";
	
}
